Search code examples
mongodbgomgo

mongodb query with go dynamic


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.


Solution

  • 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 $and key (if you want them in logical AND connection, or $or if you want logical OR), whose value in the map is the slice of filters (documents).

    This is how easy it is:

    // filters contains all the filters you want to apply:
    filters := []bson.M{
        bson.M{"age": bson.M{"$gt": 20}},
        bson.M{"name": "Bob"},
    }
    
    // filter is a single filter document that merges all filters
    filter := bson.M{"$and": filters}
    
    // And then:
    err := coll.Find(filter).All(&persons)