I would like to build a mongo query dynamic but searching in google, i don't understand why the first query returns null.
matches := []bson.M{bson.M{"$match": bson.M{"age": bson.M{"$gt": 20}}}}
err2 := coll.Find(matches).All(&persons)
This shows the expected rows:
err2 = coll.Find(bson.M{"age": bson.M{"$gt": 20}}).All(&persons)
Would you have a simple example how to build query with two parameter, please?
Thank you.
Your first example doesn't work because
Collection.Find()expects a single filter document and you pass a slice of documents to it.A single document may contain multiple filters, e.g.
bson.M{"age": bson.M{"$gt": 20}, "name": "Bob"}, so in practice this doesn't pose a restriction.If you have multiple filter documents and you want to apply all, you have to "merge" them into a single document.
A general solution is to create a document with an
$andkey (if you want them in logical AND connection, or$orif you want logical OR), whose value in the map is the slice of filters (documents).This is how easy it is: