I'm having JSON data in mongo and I want to fetch only those domains where activeInd=true from an array. Below is the sample data in the DB I have.
{
"organizationId" : 339975,
"domains" : [
{
"application" : "ABC",
"activeInd": true,
"subdomain":["URL1","url2"]
},
{
"application" : "mno",
"activeInd": false,
"subdomain":["URL3","url4"]
},
{
"application" : "pqr",
"activeInd": false,
"subdomain":["URL","url6"]
},
{
"application" : "egh",
"activeInd": true,
"subdomain":["URL11","url16"]
}]
}
And I have tried some solutions like below
db.collectionName.aggregate([{$project: {organizationId: {$eq: ["$organizationId", 339975]},
domains:{
$filter: {
input: "$domains",
as : "domains",
cond: {$eq: ["$$domains.activeInd", true]}
}
}}
}])
This is fetching data from organizationId as well but my requirement is in the given organizationId the domains should be fetched where activeInd=true In general i need output like below sample Required output
{
"organizationId" : 339975,
"domains" : [
{
"application" : "ABC",
"activeInd": true,
"subdomain":["URL1","url2"]
},
{
"application" : "egh",
"activeInd": true,
"subdomain":["URL11","url16"]
}]
}
Can someone help me please.
CodePudding user response:
Maybe $filter as follow:
db.collection.aggregate([
{
$match: {
organizationId: 339975
}
},
{
$project: {
domains: {
$filter: {
input: "$domains",
as: "item",
cond: {
$eq: [
"$$item.activeInd",
true
]
}
}
}
}
}
])
explained:
- In the match stage you fetch only the necessary organizationId documents
- In the filter stage you get only the activeInd items from domains
