我需要做一个特殊的查询。我有一份可用于生产的元素 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"
}
],
}
示例列表可能如下所示: [“木材”、“啤酒”、“煤炭”、“油漆”、“铜矿”]
这应该返回“煤炭”、“铜”和“木制玩具”的文件,因此它们的所有要求都在列表中。 “椅子”缺少“钉子”,“熨斗”缺少“Ironore”。
(抱歉我的英语不好;))
最佳答案
您可以使用 $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"
]
}}
])
关于node.js - 异常的 Mongodb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41044230/