Reputation: 2668
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{}.
Upvotes: 16
Views: 29602
Reputation: 21
Another point that I came across by the Vim IDE that I use. It was for this line:
findOptions := options.Find()
// Sort by `price` field descending
findOptions.SetSort(bson.D{{"price", -1}})
db.Collection("products").Find(nil, bson.D{}, findOptions)
I got: "go.mongodb.org/mongo-driver/bson/primitive.E struct literal uses unkeyed fields" warning,(I know that many people do not care about it :ـ) Because In Go, bson.D
is a slice of bson.E
, and bson.E
should use keyed fields for proper initialization.
then you can simply put Key
and Value
to resolve that:
findOptions := options.Find()
// Sort by `price` field descending
findOptions.SetSort(bson.D{{Key: "price",Value: -1}})
db.Collection("products").Find(nil, bson.D{}, findOptions)
Upvotes: 1
Reputation: 334
Try this method
findOptions := options.Find()
// Sort by `price` field descending
findOptions.SetSort(bson.M{"price": -1})
db.Collection("products").Find(nil, bson.D{}, findOptions)
This helped me to fix my code.This problem is due to the version of go that you are using.
Upvotes: 0
Reputation: 100
Another point to note, make sure that mapping of field names are correct. In my case i was trying to sort a field createdAt
but after realized my mongodb field is mapped as createdat
.
queryOptions.SetSort(bson.D{{"createdat", -1}
Upvotes: 0
Reputation: 6528
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)
Upvotes: 8
Reputation: 91
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)
Upvotes: 4
Reputation: 5103
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)
Upvotes: 38