nanakondor
nanakondor

Reputation: 745

MongoDB go driver maintain sort order

I query my records using this code:

cur, err := collection.Find(
    ctx,
    filter,
    options.Find().SetLimit(limit).SetSort(map[string]int{"timestamp": -1, "_id": -1}),
)

But I noticed through my mongodb log that the order changes sometimes... into _id: -1, timestamp: -1 which affects the query results. How do I make sure that timestamp comes first?

Upvotes: 1

Views: 1221

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51542

A map does not have any ordering guarantees for its elements. Use a bson.D for documents where element ordering is important:

SetSort({{"timestamp",-1},{"_id":-1}})

Upvotes: 5

Related Questions