我想构建一个动态的 mongo 查询,但是在 google 中搜索,我不明白为什么第一个查询返回 null。
matches := []bson.M{bson.M{"$match": bson.M{"age": bson.M{"$gt": 20}}}}
err2 := coll.Find(matches).All(&persons)
这显示了预期的行:
err2 = coll.Find(bson.M{"age": bson.M{"$gt": 20}}).All(&persons)
您能否提供一个如何使用两个参数构建查询的简单示例?
谢谢。
最佳答案
您的第一个示例不起作用,因为 Collection.Find()
需要一个单个过滤器文档,并且您将一部分文档传递给它。
单个文档可能包含多个过滤器,例如bson.M{"age": bson.M{"$gt": 20}, "name": "Bob"}
,所以实际上这不会造成限制。
如果您有多个过滤器文档并且想要应用所有文档,则必须将它们“合并”到一个文档中。
一般的解决方案是创建一个带有 $and
键的文档(如果您希望它们处于逻辑 AND 连接,或者如果您想要逻辑 OR,则使用 $or
),其在映射中的值是过滤器(文档)的 slice 。
就是这么简单:
// 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)
关于使用 go 动态进行 mongodb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64188601/