繁体   English   中英

猫鼬:查找所有包含在另一个数组中的数组字段的文档

[英]Mongoose: Find all documents with array field which is included in another array

因此,此示例将是这样的:

请求对以下数组进行搜索:

    ['banana', 'apple', 'orange', 'mango']

至于我的数据库,我有一个Recipe集合,其中包含一个字段ingredints是一个数组。

文件#1:

... ingredients: ['banana', 'apple'] ...

文件#2:

... ingredients: ['banana', 'apple', 'orange'] ...

文件#3:

... ingredients: ['apple', 'orange', 'kiwi'] ...

查询的输出应返回Document#1和Document#2。 (包含奇异果的文档#3,初始数组中未包含)。

您可以使用以下聚合:

db.col.aggregate([
    {
        $addFields: {
            matchingElements: { $setIntersection: [ ['banana', 'apple', 'orange', 'mango'], "$ingredients" ] }
        }
    },
    {
        $redact: {
            $cond: {
                if: { $eq: [ { $size: "$ingredients" }, { $size: "$matchingElements" } ] },
                then: "$$KEEP",
                else: "$$PRUNE"
            }
        }
    },
    {
        $project: {
            matchingElements: 0
        }
    }
])

$ setIntersection将为您提供数组中存在的ingredients中的所有项目。 然后,您可以使用$ redact来检查matchingElements是否具有与ingredients相同的大小,这意味着所有元素都匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM