如何解决聚合管道字符串形成
if (field) {
if (field === "3") {
// count_query_match = { $match:{ $and:[ {partyName:{'$regex' : '^'+search+'$','$options' : 'i'}},{company_id:new mongoose.Types.ObjectId(req.user.company_id)} ]} }
count_query_match = { $match: { partyName: { '$regex': '^' + search + '$','$options': 'i' },company_id: new mongoose.Types.ObjectId(req.user.company_id) } }
} else if (field === "4") {
count_query_match = { $match: { pr_phoneNumber: { '$regex': '^' + search + '$','$options': 'i' } } }
} else if (field === "5") {
count_query_match = { $match: { vehicleNo: { '$regex': '^' + search + '$','$options': 'i' } } }
}
}
// count_query_match = {
// ...count_query_match,company_id:new mongoose.Types.ObjectId(req.user.company_id)
// }
console.log(count_query_match);
count_query_group = {
$group: {
// _id : "$partyName",_id: null,netWeight: { $sum: "$netWeight" },netweightXvalue: { $sum: "$netweightXvalue" },netValue: { $sum: "$netValue" },count: { $sum: 1 }
}
}
data5 = await Productregistration.aggregate([count_query_match,count_query_group]);
res.status(200)
.json({
success: true,count: data5.length,// data1: data5[0],data2: data5
});
如何将company_id:new mongoose.Types.ObjectId(req.user.company_id)条件添加到所有具有相同条件的聚合计数查询匹配函数中。
在普通查询中,我会这样做,但会添加常见条件
query = {
...query,company_id: req.user.company_id
}
解决方法
您可以使用以下两种方法中的任何一种:
直接将常见条件作为属性添加到 $match
if (field) {
if (field === "3") {
count_query_match = { $match: { partyName: { '$regex': '^' + search + '$','$options': 'i' } }}
} else if (field === "4") {
count_query_match = { $match: { pr_phoneNumber: { '$regex': '^' + search + '$','$options': 'i' } } }
} else if (field === "5") {
count_query_match = { $match: { vehicleNo: { '$regex': '^' + search + '$','$options': 'i' } } }
}
}
count_query_match["$match"].company_id = company_id: new mongoose.Types.ObjectId(req.user.company_id);
使用另一个变量match
来形成动态查询,然后在常见条件下进行传播
let match;
if (field) {
if (field === "3") {
match = { partyName: { '$regex': '^' + search + '$','$options': 'i' }};
} else if (field === "4") {
match = { pr_phoneNumber: { '$regex': '^' + search + '$','$options': 'i' } };
} else if (field === "5") {
match = { vehicleNo: { '$regex': '^' + search + '$','$options': 'i' } };
}
}
const count_query_match = {
$match: {
...match,company_id:new mongoose.Types.ObjectId(req.user.company_id)
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。