I had a working mongoose query using Aggregate where I filter data based on a value inside an array of objects and am running into trouble due to change in requirements.
This is my how my data looks like in MongoDB (it has been filled with dummy data)
{
"_id" : ObjectId("5ef44528af5a1a2a641cd52b"),
"active" : true,
"name" : "CompanyA",
"contacts" : [
{
"secondary_emails" : [],
"_id" : ObjectId("5f19727495f4da29403923e3"),
"email" : "[email protected]",
"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"
],
}
]}
Objective: Filter services on the basis of the category provided by the user (assuming its "SD-WAN"), before the category was singular and now its an array of values, since one service can belong to multiple categories
Previous Solution My mongoose query, that I was using for singular category values was as below:
db.Collection("suppliers").aggregate([
{
$project: {
services: {
$filter: {
input: "$services",
as: "services",
cond: { $eq: ["$$services.category", "SD-WAN" ] },
},
},
},
},
{ $match: { services: { $exists: true, $not: { $size: 0 } } } },
]);
I am having trouble trying to search for SD-WAN inside $$services.categories which is an array of values. Is there any way to update the above query to search for the value in services.categories array using the $eq pipeline operator or some other solution perhaps.
Expected Result
"_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"
],
}
]
If anyone can help me out on this, it would be really appreciated. If more information is required, please ask. Thank you.
Here what you looking for.
[
{
$unwind: "$services"
},
{
$match: {
"services.categories": "SD-WAN"
}
},
{
$group: {
_id: "$_id",
active: {
$first: "$active"
},
name: {
$first: "$name"
},
contacts: {
$first: "$contacts"
},
services: {
$addToSet: "$services"
}
}
}
]
$unwind for flatten the array$match to filter$group to group it back.We flatten services only. That why I use $addToSet
Working Mongo playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With