I stumbled across very strange behaviour in my aggregate query that I am running in Swift through:
db.collection(withName: "Example")..aggregate(pipeline: aggregatePipeline) { ... }
This is the stage that is behaving very strangely:
let aggregatePipeline: [Document] = [
[
"$sort": [ "seen": 1 , "score": -1, "_id": -1 ]
]
]
The results I get are sorted by these three keys, but in seemingly arbitrary sorting order each time I run the query. So sometimes the “seen” sorting is prioritised (as it should be) but sometimes it sorts first by “_id”, or “score”. When I print the stage right after defining it by running:
print(aggregatePipeline[0])
I do see a the probable reason for those odd results…
first run:
["$sort": Optional(RealmSwift.AnyBSON.document(["_id": Optional(RealmSwift.AnyBSON.int64(-1)), "seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1))]))]
second run:
["$sort": Optional(RealmSwift.AnyBSON.document(["seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1)), "_id": Optional(RealmSwift.AnyBSON.int64(-1))]))]
how can I write this query with a definitive sorting order (having field order fixed)? I found nothing in the relevant docs or especially this where it should definitely be stated how this could be accomplished, since this would be the most sensible way, but obviously is the wrong way of doing it.
Edit: this seems to be a serious bug in RealmSwift, since field order should normally be preserved according to this. but is not preserved in the Swift SDK as shown above!