Dimas Angga Saputra
Dimas Angga Saputra

Reputation: 221

Mongodb count sum of fields in a collection with conditions

I have collections in mongoDb like this:

{
  _id: ObjectId(""),
  fieldA: "123",
  fieldB: {
      subFieldB:[
           {
             fieldC: ""
           },
           {
             fieldC: ""
           },
           {
             fieldC: ""
           }
      ]
  }    
},
{
  _id: ObjectId(""),
  fieldA: "123",
  fieldB: {
      subFieldB:[
           {
             fieldC: ""
           },
           {
             fieldC: ""
           },
           {
             fieldC: ""
           }
      ]
  }    
},
{
  _id: ObjectId(""),
  fieldA: "456",
  fieldB: {
      subFieldB:[
           {
             fieldC: ""
           },
           {
             fieldC: ""
           },
           {
             fieldC: ""
           }
      ]
  }    
}

I want to get sum of number of subFieldB where fieldA is "123" So the goal is getting something like {sumOfSubFieldB: 6}

I tried aggregate like:

db.collection.aggregate([
    {
        $match : { "fieldA" : "123" }
    },
   {
      $project: {
         numberOfFieldB: { $cond: { if: { $isArray: "$fieldB.subFieldB" }, then: { $size: "$fieldB.subFieldB" }, else: "NA"} },
      }
   }
] )

So far I get sum of fieldB per doc like:

{
    "_id" : ObjectId(""),
    "numberOfFieldB" : 3
}

{
    "_id" : ObjectId(""),
    "numberOfFieldB" : 3
}

How should I do the query to get total number of fieldB? Thank you

Upvotes: 0

Views: 25

Answers (1)

Raymond Reddington
Raymond Reddington

Reputation: 1837

Try this one, or something similar with $group:

db.collection.aggregate(
    [{
        $match: {
            "fieldA": "123"
        }
    }, {
        $group: {
            _id: "$fieldA",
            count: { 
                $sum: { $size: "$fieldB.subFieldB" } }
        }
    }]
);

Upvotes: 1

Related Questions