【发布时间】:2020-11-19 22:00:33
【问题描述】:
我有一个使用 Aggregate 的工作 mongoose 查询,我根据对象数组中的值过滤数据,但由于需求变化而遇到麻烦。
这是我的数据在 MongoDB 中的样子(它已经填充了虚拟数据)
{
"_id" : ObjectId("5ef44528af5a1a2a641cd52b"),
"active" : true,
"name" : "CompanyA",
"contacts" : [
{
"secondary_emails" : [],
"_id" : ObjectId("5f19727495f4da29403923e3"),
"email" : "contact@gmail.com",
"designation" : "VP Cloud & Security",
"address" : "",
"name" : "Ron"
}
],
"services" : [
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52d"),
"name" : "Company Management",
"title" : "Company Helpline",
"description" : "Offering voice, meetings, collaboration and contact center all on one cloud platform.",
"categories" : [
"SD-WAN",
"Security and Compliance"
],
"sub_categories" : [
"Solution"
],
},
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52c"),
"name" : "Company HR",
"title" : "Human Resources",
"description" : "Offering HR Services to all",
"categories" : [
"HR", "Company"
],
"sub_categories" : [
"Solution"
],
}
]}
目标:根据用户提供的类别(假设其“SD-WAN”)过滤服务,之前类别是单数,现在是一组值,因为一个服务可以属于多个类别
以前的解决方案 我用于奇异类别值的猫鼬查询如下:
db.Collection("suppliers").aggregate([
{
$project: {
services: {
$filter: {
input: "$services",
as: "services",
cond: { $eq: ["$$services.category", "SD-WAN" ] },
},
},
},
},
{ $match: { services: { $exists: true, $not: { $size: 0 } } } },
]);
我在尝试在 $$services.categories 中搜索 SD-WAN 时遇到问题,这是一个值数组。有没有办法更新上述查询以使用 $eq 管道运算符或其他解决方案搜索 services.categories 数组中的值。
预期结果
"_id" : ObjectId("5ef44528af5a1a2a641cd52b"),
"services" : [
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52d"),
"name" : "Company Management",
"title" : "Company Helpline",
"description" : "Offering voice, meetings, collaboration and contact center all on one cloud platform.",
"categories" : [
"SD-WAN",
"Security and Compliance"
],
"sub_categories" : [
"Solution"
],
}
]
如果有人能帮助我解决这个问题,我将不胜感激。如果需要更多信息,请询问。谢谢。
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework mongoose-schema