【问题标题】:mongodb query with go dynamic带有go动态的mongodb查询
【发布时间】:2021-01-19 03:17:53
【问题描述】:

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

您能否举一个简单的例子,如何使用两个参数构建查询?

谢谢。

【问题讨论】:

  • Find() 需要一个过滤器 document ,在您的第一个示例中,您传递了一段文档。它与动态无关。单个文档可能包含多个过滤器,例如bson.M{"age": bson.M{"$gt": 20}, "name": "Bob"}。你有什么问题?
  • 问题是为什么匹配 := []bson.M{bson.M{"$match": bson.M{"age": bson.M{"$gt": 20} }}} 不管用。以及如何动态连接多个过滤器。

标签: mongodb go mgo


【解决方案1】:

您的第一个示例不起作用,因为 Collection.Find() 需要一个单个过滤器文档,而您将一个文档片段传递给它。

单个文档可能包含多个过滤器,例如bson.M{"age": bson.M{"$gt": 20}, "name": "Bob"},所以实际上这不会构成限制。

如果您有多个过滤器文档并且想要应用所有过滤器文档,则必须将它们“合并”到单个文档中。

一般的解决方案是创建一个带有 $and 键的文档(如果您希望它们处于逻辑 AND 连接,或者 $or 如果您希望逻辑 OR),其在映射中的值是过滤器切片(文档)。

这就是这么简单:

// 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2011-09-29
    相关资源
    最近更新 更多