[英]Mongo Array Query Count
Sample Collection样品采集
[
{
products: [
{name: 'apple'}, {name: 'mango'}, {name: 'orange'}
]
},
{
products: [
{name: 'banna'}, {name: 'grapes'}, {name: 'orange'}
]
}
]
I want a query to know if which document contains atleast 2 of my searched products我想要查询以了解哪个文档是否包含我搜索的至少 2 个产品
for example..例如..
collection.find({ products: {$in: ['apple', 'mango', 'durian', 'avocado', 'orange']} })
but this only checks if it contains one of those products.但这仅检查它是否包含其中一种产品。 I wanna know if a certain documents containls atleast 2 of the product im searching
我想知道某些文件是否包含我正在搜索的至少 2 个产品
You can either add some code so manipulate the query structure or you have to use an aggregation pipeline.您可以添加一些代码来操作查询结构,或者您必须使用聚合管道。
Option 1 (recommended), use the aggregation pipeline with $filter :选项 1(推荐),将聚合管道与$filter一起使用:
let fruits = ['apple', 'mango', 'durian', 'avocado', 'orange'];
collection.aggregate([
{
$match: {
"products.name": {$in: fruits}
}
},
{
$project: {
good_products_size: {
$size: {
$filter: {
input: "$products",
as: "product",
cond: {$in: ["$$product.name", fruits]}
}
}
}
}
},
{
$match: {
good_products_size: {$gt: 1}
}
}
]);
Option 2 (less recommended imo), generate all possible pairs from the fruits array and use $all :选项 2(不太推荐 imo),从 fruits 数组中生成所有可能的对并使用$all :
let fruits = ['apple', 'mango', 'durian', 'avocado', 'orange'];
let queryOrConds = [];
for (let i = 0; i < fruits.length - 1; i++) {
for (let j = i; j < fruits.length - 1; j++) {
queryOrConds.push({"products.name": {$all: [fruits[i], fruits[j]]}})
}
}
collection.find({ $or: queryOrConds })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.