使用 go 动态进行 mongodb 查询

标签 mongodb go mgo

我想构建一个动态的 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/

相关文章:

go - socket.go 中 SimpleQuery 中的本地互斥锁

mongodb - 使用存储在数组中的 _id 从 golang 查询 mongodb

mongodb - 清理 Express 应用程序中的输入字段

Spring Data MongoDB 与 Java 8 LocalDate MappingException

mongodb - 为什么 MongoDB shell new ISODate(0001-01-01) 返回日期 1901-01-01

amazon-web-services - 如何将 AWS GO SDK 与 RESTful API 结合使用?

mongodb - 如何在go mongo-driver库中使用Find()。Select()。One()

mongodb - 使用 $pull 和 $[identifier] 从嵌套数组中删除对象 (mongoDB 3.6)

go - 扫描仪可以有 slice 接收器吗?

mongodb - mgo golang 不使用 $set 更新空数组