Reputation: 745
I'm using Mongodb go driver and still figuring out how to aggregate. My question is, if I use []bson.M as pipelines as shown by the code below:
collection.Aggregate(
ctx,
[]bson.M{
bson.M{
"$match": filter,
},
bson.M{
"$sort": sort,
},
},
)
Is it certain that the match is always first before the sort? Should I switch to mongo.Pipeline ([]bson.D) instead for 100% maintained order? thanks
Upvotes: 1
Views: 1312
Reputation: 417947
[]bson.M
is a slice, and slices do maintain order. $match
will always be taken first, and $sort
as second.
bson.M
is a map, so if you have multiple elements (key-value pairs) in it, order inside it is not maintained.
You may use whichever is more convenient for you ([]bson.M
or []bson.D
or mongo.Pipeline
).
You must use bson.D
when order is important inside a single document, e.g. when sorting by multiple fields. For details, see bson.D vs bson.M for find queries.
Upvotes: 1