mongodb - 使用嵌套结构的逻辑运算符查找查询?

标签 mongodb go mongodb-query mgo

我想使用 $or 查找包含任何给定参数的条目。数据库条目如下所示

"resources" : {
    "compute" : "compute4",
    "storage" : "storage3",
    "network" : "network2"
},

我想找到满足资源内任何字段的条目。

bkCollection.Find(bson.M{"resources": bson.M{
    "compute": filter.Resources.Compute, "$or",
    "storage": filter.Resources.Storage, "$or",
    "network": filter.Resources.Network}}).All(&result)

最佳答案

您需要使用 $or 构造与此 mongo shell 查询等效的内容 运算符:

db.collection.find({
    "$or": [
        { "resources.compute" : "compute5" },
        { "resources.storage" : "storage3" },
        { "resources.network" : "network1" }
    ]
})

go 中,这将被构造为:

bkCollection.Find(bson.M{ "$or": []bson.M{ 
    bson.M{ "resources.compute": filter.Resources.Compute }, 
    bson.M{ "resources.storage": filter.Resources.Storage },
    bson.M{ "resources.network": filter.Resources.Network }
}}).All(&result)

关于mongodb - 使用嵌套结构的逻辑运算符查找查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364033/

相关文章:

node.js - 尝试使用唯一索引保存 Mongoose 文档时, Node 服务器崩溃

python - 更新mongo中的字段类型

javascript - Angular POST 请求不起作用

mongodb - 在嵌套数组中添加新项目

node.js - 如何将服务器的数据暴露给客户端

go - gorilla cookie session 会持续服务器重建吗?

regex - 来自abc.xyz.cbf201的Go中的正则表达式值cbf

python - 在mongo/python中查找()指定数量的记录

mongodb - 使用 $unwind 时可以避免两次使用相同的 $match 标准吗?

json - 如何以 Sendgrid API 接受的格式将 html 嵌入到 json 中?