2

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.

2
  • 2
    Find() expects a filter document and in your first example you pass a slice of documents. It has nothing to do with being dynamic. A single document may contain multiple filters, e.g. bson.M{"age": bson.M{"$gt": 20}, "name": "Bob"}. What is your question? Commented Oct 3, 2020 at 21:21
  • The question is why the matches := []bson.M{bson.M{"$match": bson.M{"age": bson.M{"$gt": 20}}}} is not working. And how could I concat multiple filters dynamically. Commented Oct 4, 2020 at 14:39

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.