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{}.
MongoDB does not guarantee order if ties occur. For example, in the sample data, there is a tie for the rating in the following documents: To guarantee a specific order for documents when ties occur, specify additional fields to sort by. The following example specifies an ascending sort on the rating field, then a descending sort on the type field:
The MongoDB supported driver for Go. Go 1.10 or higher if using the driver as a dependency. Go 1.17 or higher if building the driver yourself. We aim to support the latest versions of Go. MongoDB 2.6 and higher. The recommended way to get started using the MongoDB Go driver is by using Go modules to install the dependency in your project.
To get started with the driver, import the mongo package and create a mongo.Client with the Connect function: import ( "context" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" ) ctx, cancel := context. WithTimeout ( context. Background (), 10*time.
The MongoDB Go Driver supports wire protocol compression using Snappy, zLib, or zstd. To run tests with wire protocol compression, set MONGO_GO_DRIVER_COMPRESSOR to snappy, zlib, or zstd. For example: Ensure the --networkMessageCompressors flag on mongod or mongos includes zlib if testing zLib compression.
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)
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With