Ad

Unable To Fetch Data Based On Boolean Value In Mongodb

- 1 answer

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.

Ad

Answer

Maybe $filter as follow:

test here

 db.collection.aggregate([
   {
    $match: {
      organizationId: 339975
    }
  },
   {
$project: {
  domains: {
    $filter: {
      input: "$domains",
      as: "item",
      cond: {
        $eq: [
          "$$item.activeInd",
          true
             ]
          }
        }
      }
   }
 }
])

explained:

  1. In the match stage you fetch only the necessary organizationId documents
  2. In the filter stage you get only the activeInd items from domains
Ad
source: stackoverflow.com
Ad