Siraj ul Haq
Siraj ul Haq

Reputation: 885

Mongoose count items in sub document

I have following schema:

{
    _id: 1,
    post: 'content',
    comments: [
        {
            id: 1,
            items: ['<other_doc_id',...] // assume 3 items
        },
        {
            id: 2,
            items: ['<other_doc_id',...] // assume 2 items
        }
    ]
}

I want to count number of items for all documents in a collection, like in above scenario it should return 5, and if we have another document with same comments then it should return 10.

UPDATE This is my sample data

"comments": [
    {
        "id": {
            "$oid": "5a201f6d7295d76514a69a7c"
        },
        "_id": {
            "$oid": "5a2e84cc9735111c147a359f"
        },
        "tags": [
            {
                "$oid": "5a251acb6eba8810f97e7abc"
            },
            {
                "$oid": "5a251ae66eba8810f97e7abd"
            }
        ],
        "items": [
            {
                "$oid": "5a201f767295d76514a69a7d"
            },
            {
                "$oid": "5a2512a1dc9a8c106c82226d"
            }
        ]
    }
],

QUERY

posts.aggregate([{
    "$project": {
        "count": {
            "$sum": {
                "$map": {
                    "input": "comments",
                    "as": "result",
                    "in": {
                        "$size": "$$result.items"
                    }
                }
            }
        }
    }
}]);

Upvotes: 0

Views: 1043

Answers (1)

s7vr
s7vr

Reputation: 75924

You can use $map to count the $size of each items in comment array of documents followed by $sum to count all sizes.

db.collection_name.aggregate([
  {
    "$project": {
      "count": {
        "$sum": {
          "$map": {
            "input": "$comments",
            "as": "result",
            "in": {
              "$size": "$$result.items"
            }
          }
        }
      }
    }
  }
])

Upvotes: 4

Related Questions