[GODRIVER-1610] bson.M can't be used as a sort document Created: 08/May/20  Updated: 27/Oct/23  Resolved: 11/May/20

Status: Closed
Project: Go Driver
Component/s: CRUD
Affects Version/s: 1.3.2, 1.3.3
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: TheKaobkaob . Assignee: Unassigned
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

when use multi field to sort, probably different results



 Description   

type AB struct

{ A int32 bson:"A" B int32 bson:"B" }

func TestSort(t *testing.T) {
mongodb.Init()
defer mongodb.Close()

mongodb.GetTrainingDB().Collection("TestSort").Drop(context.Background())

for i := 0; i < 5; i++ {
mongodb.GetTrainingDB().Collection("TestSort").InsertOne(context.Background(), bson.M

{"A": i, "B": rand.Int31n(10)}

)
mongodb.GetTrainingDB().Collection("TestSort").InsertOne(context.Background(), bson.M

{"A": i, "B": rand.Int31n(10)}

)
}

for i := 0; i < 100; i++ {
sortABList := []AB{}
theOption := options.Find().SetSort(bson.M

{"A": -1, "B": -1}

)
theCur, _ := mongodb.GetTrainingDB().Collection("TestSort").Find(context.Background(), bson.M{}, theOption)
defer theCur.Close(context.Background())

for theCur.Next(context.Background())

{ var theValue AB theCur.Decode(&theValue) sortABList = append(sortABList, theValue) }

for i := 0; i < len(sortABList)-1; i++ {
fmt.Println(sortABList[i])
if sortABList[i].A < sortABList[i+1].A

{ t.Fatalf("sort error! %d less then %d", sortABList[i].A, sortABList[i+1].A) }

}
fmt.Println()
}

}



 Comments   
Comment by TheKaobkaob . [ 11/May/20 ]

When I change the sorting code, it's work. Thank you for your help.

theOption := options.Find().SetSort(bson.D{bson.E

{Key: "A", Value: -1}

, bson.E{Key: "B", Value: -1}})

Comment by Divjot Arora (Inactive) [ 08/May/20 ]

Hi kaobkaob0812@gmail.com,

Thank you for the detailed report and code sample. I think this is happening because the code uses. bson.M for the sort document. The bson.M type wraps a Go map and maps in the language are intentionally do not preserve insertion order when iterating. This means that the actual sort document sent to the server could be marshalled as {b: -1, a: 1} when executing the Find if that's the order the language gives us when we iterate over the map.

Can you try using an order-preserving type like bson.D for the SetSort option and see if that fixes the issue?

– Divjot

Generated at Thu Feb 08 08:36:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.