Search code examples
mongodbgoquery-optimizationmongo-go

bson.D vs bson.M for find queries


This specifc question is in relation to using mongodb with the golang package mongo-driver, but I would assume this applies across most interfaces with mongodb.

When using Find to query some data from a collection, we can use both the bson.M- and bson.D-type to specify the filter for this find.

As per the documentation bson.D should be used if the order of elements matters and bson.M should be used otherwise.

D is an ordered representation of a BSON document. This type should be used when the order of the elements matters, such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.

Now my question is whether the use of either of these, i.e. ordered vs unordered, structures has an effect on the query plan generated by the mongo query optimizer.

In a classic SQL database the order usually doesn't matter as the optimizer is smart enough to use summary statistics, indexes, etc. to determine which queries to execute first.

Can I assume this to be the case here as well, or does using an ordered structure to query my collection somehow interfere with this / does using an ordered structure work similar to using optimizer hints? If there is some interference, is this influenced at all by if the fields to search through are indexed?


Solution

  • You may use bson.M for the filter, it usually results in shorter and clearer filter declaration, the order of fields doesn't matter, the MongoDB server is smart enough to find matching indices regardless of the used order. E.g. if you have a compound index with fields A and B, using a bson.D filter listing B first then A will not prevent the server to use the existing index. So in this case you may use bson.M and bson.D, it doesn't matter.

    The order does matter when you specify sort fields for example. It does matter if you sort by field A then by field B, it may be a completely different order than sorting by B first and then by A. So when you specify a sort document having multiple fields, you should definitely use bson.D.

    The order may also matter (to you) when you insert a new document for example. If you use a bson.M as the document, the order of fields is not guaranteed to be the same in all your documents. When you use bson.D, then the order in the saved document will match the order as you list the fields in bson.D.