0

I want to count specific objects if present in collections like:

{
  id: 1,
  obj1: {...},
  obj2: {...}
},{
  id: 2,
  obj2: {...}
},{
  id: 3,
  obj1: {...},
  obj3: {...}
}

In above example i need the sum of count of objects(i.e. obj1, obj2, obj3). And query should return 5 in above scenario.

2
  • these are always named obj1, obj2, obj3? Three of them? Commented Jan 15, 2018 at 14:23
  • yes, names will always be same Commented Jan 15, 2018 at 14:26

1 Answer 1

1

You can try the below $group aggregation.

$cond with $ifNull expression to check for existence of field, output 1 when present 0 when absent.

inner $sum to count values in each document with outer $sum to sum the values across collection.

db.col.aggregate([
  {
    "$group":{
      "_id":null,
      "count":{
        "$sum":{
          "$sum":[
            {"$cond":[{"$ifNull":["$obj1",false]},1,0]},
            {"$cond":[{"$ifNull":["$obj2",false]},1,0]},
            {"$cond":[{"$ifNull":["$obj3",false]},1,0]}
          ]
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

I have replaced inner sum with add and it worked as needed, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.