[NEED HELP] - Problem with sorting in Mongo Find query

Hello Mongo Fam,

In my mongo collection, I have the “_id” which is object id key and an “priority” key which is an integer value. I’m applying the find query and sorting the data with {priority, -1}, {_id, 1}. But sometimes the “_id” sorting is happening first and then priority sorting where opposite should happen. The data is not coming as expected in these cases. The ordering of sorting is changing. Can you please give a solution to this?

It would be a major flaw if that would really happen. Most likely you are misusing find. Please share the exact code you are using.

opts := options.Find().SetSort(sortingOptionsBson).SetLimit(o_limit).SetSkip(o_skip)
cur, err = coll.Find(ctx, filter, opts)
// o_limit, o_skip have no issues. They are present above this line.
For sortingOptionsBson it would be like 
sortingOptionsBson := bson.D{{"priority", -1},{"_id", 1}}

These are the inputs to the Find query. Can you suggest an alternate to this so that the priority sorting happens first and id sorting happens second all the time?

Please tag your thread with the programming language you are using.

I am not familiar with the syntax

In JSON, it should be { “priority” : -1 , “_id” : 1 }. I do not know if the above code produce the correct object.

How is options variable defined?

How is ctx variable defined?

Are you sure coll always refer to the collection that has the index?

I’m using Golang

opts := options.Find().SetSort(sortingOptionsBson).SetLimit(o_limit).SetSkip(o_skip)

Options is defined above here

ctx is passed from the function parameters where this code resides in 

Yes I’m sure, coll represents the collection that has the index

Hope this can clear those queries

From the little I understand, the code

sets the variable opts from an expression that starts with the global variables options. We need to know how options is defined. May be someone with golang driver expertise knows that options is part of the driver. Hopefully this someone car carry on.


These are the mongo-drivers that I’m using

What would help at this point is that if you could share the explain plan of your query.

I’m using Golang. In my mongo collection, I have the “_id” which is object id key and an “priority” key which is an integer value. I’m applying the find query and sorting the data with {priority, -1}, {_id, 1} like shown below.

sortingOptionsBson := bson.D{{"priority", -1},{"_id", 1}}

My code would look something like this

// limit and offset values are passed from the arguments of the function where this code resides
// the problem lies with SetSort()
sortingOptionsBson := bson.D{{"priority", -1},{"_id", 1}}
opts := options.Find().SetSort(sortingOptionsBson).SetLimit(o_limit).SetSkip(o_skip)
cur, err = coll.Find(ctx, filter, opts)

Sometimes, the sort would be done based on “_id” first and then “priority” which should not be done.
I want to avoid this misordering and always want the priority sorting to happen first and _id sorting to happen second. What is the issue here and how can it be solved?

I want to reiterate:

We could also use sample documents that are wrongly sorted. It could also be useful to get sample documents that are correctly sorted.

Are the wrongly sorted documents reside on the same server as the one correctly sorted?

Could anyone with golang experience confirm that the code

generates a document equivalent to the JSON:

SO on how to run an explain with GO:

1 Like

I saw a different syntax for bson in Help golang Aggregate Query

And like I wrote I do not know golang but I feel that

bson.M{ "priority" : -1 , "_id" : 1}

might be the correct way to specify the sort you want.

@Krishna_Chaitanya4 It’s not immediately clear what could be going wrong. The sort document looks correct

and the rest of the code you posted seems correct.

I have some questions to help troubleshoot:

  • Can you give examples of the data in the collection you’re querying and examples of the out-of-order results you’re seeing?
  • What version of the MongoDB Go Driver are you using?
  • What version of MongoDB are you using?
  • What database topology are you using? (e.g. standalone, replica set, sharded cluster, Atlas Serverless, etc)

I attempted to reproduce the issue you described using MongoDB 6.0 and Go Driver v1.12.1, but never got out-of-order results. Here’s the code I used to attempt to reproduce the issue:

func main() {
	client, err := mongo.Connect(
	if err != nil {
	defer client.Disconnect(context.Background())

	coll := client.Database("test").Collection("priority_order")

	// Drop the collection so we start with an empty collection.
	if err := coll.Drop(context.Background()); err != nil {

	// Insert 20 docs with an integer "priority" field.
	var docs []any
	for i := 0; i < 20; i++ {
		docs = append(docs, bson.D{{"priority", i}})
	_, err = coll.InsertMany(context.Background(), docs)
	if err != nil {

	// Find the documents in reverse priority order, 2 at a time.
	for i := 0; i < 10; i++ {
		opts := options.Find().
			SetSort(bson.D{{"priority", -1}, {"_id", 1}}).
			SetSkip(int64(i * 2))
		cur, err := coll.Find(context.Background(), bson.D{}, opts)
		if err != nil {

		for cur.Next(context.Background()) {
		if err := cur.Err(); err != nil {

// Output:
// {"_id": {"$oid":"64dfadfed96b783d87d5928a"},"priority": {"$numberInt":"19"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59289"},"priority": {"$numberInt":"18"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59288"},"priority": {"$numberInt":"17"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59287"},"priority": {"$numberInt":"16"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59286"},"priority": {"$numberInt":"15"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59285"},"priority": {"$numberInt":"14"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59284"},"priority": {"$numberInt":"13"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59283"},"priority": {"$numberInt":"12"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59282"},"priority": {"$numberInt":"11"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59281"},"priority": {"$numberInt":"10"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59280"},"priority": {"$numberInt":"9"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927f"},"priority": {"$numberInt":"8"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927e"},"priority": {"$numberInt":"7"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927d"},"priority": {"$numberInt":"6"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927c"},"priority": {"$numberInt":"5"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927b"},"priority": {"$numberInt":"4"}}
// {"_id": {"$oid":"64dfadfed96b783d87d5927a"},"priority": {"$numberInt":"3"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59279"},"priority": {"$numberInt":"2"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59278"},"priority": {"$numberInt":"1"}}
// {"_id": {"$oid":"64dfadfed96b783d87d59277"},"priority": {"$numberInt":"0"}}