[英]Mongoose find all documents that have a string in an array
[英]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.