1

I want count of sub document in array, without using $unwind and $group , if possible.

[{
    "_id" : ObjectId("5aefead0227bc943df3fedff"),
    "doc" : [ 
        {
            "_id" : ObjectId("5af0e877227bc943df401337"),
            "shared_with" : [ 
                {
                    "user_id" : ObjectId("5ad5e57b473e2606e0d443c3"),
                    "_id" : ObjectId("5af0e877227bc943df401339")
                }, 
                {
                    "user_id" : ObjectId("5adbf029b2da8e380b9321b6"),
                    "_id" : ObjectId("5af0e877227bc943df401338")
                }
            ]
        }, 
        {
            "_id" : ObjectId("5b4d856702d7f52974aab962"),
            "shared_with" : [ 
                {
                    "user_id" : ObjectId("5ac7083ce56c9d304f2fa533"),
                    "_id" : ObjectId("5b4d856702d7f52974aab963")
                }
            ]
        }
    ]
}]

above is the result i'm getting after lookup, i want to count total number of sub document ('shared_with') inside array ('doc') with documents,

so my desired output is as follow,

[{
   "_id" : ObjectId("5aefead0227bc943df3fedff"),
   "count":3`enter code here`
}]
0

2 Answers 2

2

You can try $map aggregation first to loop over the doc and find the $size of the shared_with array and then count all the shared_with with $sum aggregation

db.collection.aggregate([
  { "$project": {
    "doc": {
      "$map": {
        "input": "$doc",
        "as": "do",
        "in": {
          "_id": "$$do._id",
          "count": { "$size": "$$do.shared_with" }
        }
      }
    }
  }},
  { "$project": {
    "count": { "$sum": "$doc.count" }
  }}
])

Output

[
  {
    "_id": ObjectId("5aefead0227bc943df3fedff"),
    "count": 3
  }
]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use $reduce to count the inner subdocuments.

Something like

db.colname.aggregate([
  {"$project":{
    "count":{
      "$reduce":{
        "input":"$doc",
        "initialValue":0,
        "in":{"$add":["$$value",{"$size":"$$this.shared_with"}]}
      }
    }
  }}
]) 

Comments

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.