是否有方法使用对象数组作为搜索参数来搜索mongodb数据库?
假设我有以下搜索首选项:
preferences = [{
product: "PRODUCT_A",
minqty: 5,
maxqty: 50
},
{
product: "PRODUCT_B",
minqty: 100,
maxqty: 500
}
]
在我的数据库中,我有具有以下结构的作业:
{
jobName: "job name",
items: [{
product: "PRODUCT_A"
qty: 25
},
{
product: "PRODUCT_F"
qty: 300
}
]
}
我想使用首选项查询数据库,并返回与匹配的任何作业--至少一个条件的。
尝试1:
我设法使用我所有的首选项作为筛选器,但是$match
是累加的,它的编写方式类似于javascript中的&&
。我的目标是“匹配这个||
匹配那个”。
let pipeline = [];
preferences.map((item) => {
let search = {
product: item.product,
quantity: { $gte: item.minqty, $lte: item.maxqty },
};
return pipeline.push({
$match: {
items: {
$elemMatch: search,
},
},
});
});
const jobs = await Job.aggregate(pipeline);
调度2(成功):
let search = [];
preferences.map((item, index) => {
let arguments = {
product: item.product,
quantity: { $gte: item.minqty, $lte: item.maxqty },
};
search.push(arguments);
});
let pipeline = [
{
$match: {
items: {
$elemMatch: {
$or: search,
},
},
},
},
];
const jobs = await Job.aggregate(pipeline);
发布于 2021-01-17 09:42:58
使用聚合
使用$Unwind
match
与$or
$lte
和$gte
。
然后用你的尝试更新这个问题,或者发布一个新的。
https://stackoverflow.com/questions/65763499
复制相似问题