node.js - 异常的 Mongodb 查询

标签 node.js mongodb mongoose aggregation-framework

我需要做一个特殊的查询。我有一份可用于生产的元素 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/

相关文章:

javascript - 登录按钮重定向到两个页面。对于首次登录者,它会重定向到协议(protocol)页面,对于休息,它会直接重定向到主页?

mongodb - 什么是多态数据? NoSQL 数据库

node.js - $所有 mongodb Node js

node.js - 闪讯 Passport-local-mongoose

mongodb - 将 2 个 mongoDB 集合中的数据合并到 1 个文档中

javascript - 迭代时修改数组

node.js - Mongodb,查找集合是否为空,node.js

node.js - Nodejs : Writestream on windows machine

javascript - 运行 JavaScript 文件来执行 mongodb 查询

node.js - 如何在 Mongoose 中填充引用另一个模式的对象数组