[英]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.