Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Key order matter in a MongoDB BSON doc?

Tags:

mongodb

bson

I know certain commends need the hashmap / dictionary to be ordered, but does the actual BSON document in MongoDB matter and would the index still work?

E.g.

db.people.ensureIndex({LName:1, FName:1});

Would it work on both:

{LName:"abc", FName:"def"}, 
{FName:"ghi", LName:"jkl"} 

?

Thanks

like image 830
Henry Avatar asked Nov 05 '22 05:11

Henry


1 Answers

The order of a document's properties does not affect indexing.

You can see this for yourself by running this query:

db.people.find({LName: "abc"}).explain()

and then this query:

db.people.find({LName: "jkl"}).explain()

you should see that MongoDB will use the index in both cases (the cursor property should be something like "BtreeCursor LName_1_FName_1").

like image 169
Theo Avatar answered Nov 15 '22 07:11

Theo