我需要做一个特殊的查询。我有一个可用于生产的物品清单。有了这些数据,我需要查询每个类型的项目在List中的文档。一些(稍微)简单的文档看起来可能是这样的。
{
"productname": "iron",
"requirements": [
{
"ammount": 2,
"item": "coal"
},
{
"ammount": 2,
"item": "ironore"
}
],
}
{
"productname": "coal",
"requirements": [
{
"ammount": 2,
"item": "wood"
}
],
}
{
"productname": "copper",
"requirements": [
{
"ammount": 2,
"item": "coal"
},
{
"ammount": 2,
"item": "copperore"
}
],
}
{
"productname": "Chair",
"requirements": [
{
"ammount": 2,
"item": "wood"
},
{
"ammount": 2,
"item": "nails"
},
{
"ammount": 2,
"item": "paint"
}
],
}
{
"productname": "Wooden Toy",
"requirements": [
{
"ammount": 2,
"item": "wood"
},
{
"ammount": 2,
"item": "paint"
}
],
}
示例列表可能如下所示: [" wood"," beer"," coal"," paint"," copperore"]
这应归还"煤炭","铜"和#34;木制玩具"因此他们的所有要求都在列表中。对于"主席" "指甲"缺少了,并且为了铁#34; " Ironore"不见了。
(抱歉我的英文不好;))
答案 0 :(得分:0)
根据您提供的文档,如果您要查找包含requirements
coal
和coppercore
的文档,请填写以下查询:
> db.materials.find({"requirements.item" : "coal", "requirements.item": "copperore" }).pretty()
会回来:
{
"_id" : ObjectId("584990f083842cff8826d44f"),
"productname" : "copper",
"requirements" : [
{
"ammount" : 2,
"item" : "coal"
},
{
"ammount" : 2,
"item" : "copperore"
}
]
}
答案 1 :(得分:0)
如果我正确理解您的问题(我不确定),您可以使用all
运算符:
db.materials.find({"requirements.item": {$all: ["coal", "copperore"]}})
答案 2 :(得分:0)
您可以使用$redact
和$setIsSubset
作为$cond
var myList = ["wood", "beer","coal", "paint", "copperore"]
db.collection.aggregate([
{ "$match": { "requirements.item": { "$in": myList } } },
{ "$redact": {
"$cond": [
{
"$setIsSubset": [
"$requirements.item",
myList
]
},
"$$KEEP",
"$$PRUNE"
]
}}
])