简体   繁体   English

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

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

So the example for this would be something like this: 因此,此示例将是这样的:

Requesting to do a search on the following array: 请求对以下数组进行搜索:

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

As for my database, I have a Recipe collection which contains a field ingredints - being an Array. 至于我的数据库,我有一个Recipe集合,其中包含一个字段ingredints是一个数组。

Document #1: 文件#1:

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

Document #2: 文件#2:

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

Document #3: 文件#3:

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

The output of the query should return Document #1 and Document #2. 查询的输出应返回Document#1和Document#2。 (Document #3 containing kiwi which is not included in the initial array). (包含奇异果的文档#3,初始数组中未包含)。

You can use below aggregation: 您可以使用以下聚合:

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 will give you all the items from ingredients that are present in your array. $ setIntersection将为您提供数组中存在的ingredients中的所有项目。 Then you can use $redact to check if matchingElements has the same size as ingredients which means that all elements match. 然后,您可以使用$ redact来检查matchingElements是否具有与ingredients相同的大小,这意味着所有元素都匹配。

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

相关问题 ZCCADCDEDB567ABAE643E15DCF0974E503Z 查找数组中包含字符串的所有文档 - Mongoose find all documents that have a string in an array 猫鼬-通过部分匹配另一个数组来基于对象数组字段查找文档 - Mongoose - find documents based on array of objects field by partial matching another array 如何在Mongodb(Mongoid)中使用包含另一个文档的数组字段创建模型作为嵌入式文档 - How to create model with an array field which contains another documents as an embedded documents in Mongodb (Mongoid) 如何查找其特定字段不是数组类型的文档? - how to find documents that their specific field is not in array type? 在嵌入文档数组中查找特定字段 - Find specific field in an array of embedded documents 如何更新具有嵌入文档的 mongoose 数组中的许多元素 - How to Update many elements in mongoose array which has embedded documents Mongoose - 查找数组没有任何匹配项的文档 - Mongoose - Find documents where array doesn't have any matches 查找引用ID在数组中的所有文档 - Find all documents where ref ID is in array 返回数组类型字段包含确切顺序的数组的文档 - Return documents of which field of type array contains array in exact order 如何检查数组的所有对象是否包含在另一个数组中? - How to check if all objects of array are included another array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM