Golang MongoDB Driver sort

Viewed 20691

How to query find using golang mongodb driver?

I try this one :

db.Collection("products").Find(nil, bson.M{}, &options.FindOptions{Sort: "-price"})

But I got this error :

cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel

I don't know what to pass to Sort variable becuase it is an interface{}.

3 Answers

try the below code

findOptions := options.Find()
// Sort by `price` field descending
findOptions.SetSort(bson.D{{"price", -1}})


db.Collection("products").Find(nil, bson.D{}, findOptions)

I couldn't pass ‍‍bson.D to options(It caused error). but this code worked for me:

    queryOptions := options.FindOneOptions{}
    
    queryOptions.SetSort(bson.D{{"priority", -1}, {"last_error_time", 1}})

    sResult := collection.FindOne(context.TODO(), queryFilter, &queryOptions)

A few notes I've come across trying to solve a related problem:

  • If trying to sort by multiple fields be sure to use bson.D rather than bson.M because bson.M doesn't preserve order.

  • If trying to programmatically build up multiple sort fields, try
    appending bson.E to a bson.D

  • As dassum did, pass bson.M{} for an empty filter as recommended by
    the mongo documentation

Applied:

sort := bson.D{}
for _, example := examples {
    sort = append(sort, bson.E{example, 1})
}

findOptions.SetSort(sort)
db.Collection("products").Find(nil, bson.D{}, findOptions)
Related