Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-aggregation

Count Elements SubDocument that match a given criterion


I have the following document structure in mongodb

{
    "_id" : "123",
    "first_name" : "Lorem",
    "last_name" : "Ipsum",
    "conversations" : {
            "personal" : [
                    {
                            "last_message" : "Hello bar",
                            "last_read" : 1474456404
                    },
                     {
                            "last_message" : "Hello foo",
                            "last_read" : 1474456404
                    },
                    ...
            ],

            "group" : [
                    {
                            "last_message" : "Hello Everyone",
                            "last_read" : null
                    }
                    ...
            ]
    }
}

I want to count the number of conversations from the sub arrays, personal and group where the last_read is null, for a given user. Please how can I achieve this?

I tried:

db.messages.aggregate(
   [
    { $match: {"_id":"123", 'conversations.$.last_read': null }},
      {
         $group: {
            {$size: "$conversations.personal"}, {$size: "$conversations.group"}
         }
      }
   ]
);

but didn't get he desired output. Any better ideas, please?


Solution

  • The following query counts the number of sub documents under personal and group arrays that have last_read value null.

    $concatArrays combines multiple arrays into a single one. It was introduced in MongoDB 3.2.

    db.collection.aggregate([
                            { "$match": {"_id":"123", 'conversations.$.last_read': null }},
                            { "$project":{"messages":{$concatArrays : ["$conversations.personal","$conversations.group"]}}}, 
                            { "$unwind": "$messages"}, {$match:{"messages.last_read": null}}, 
                            { "$group":{"_id":null, count: {$sum:1}}}
                    ])
    

    Sample Result:

    { "_id" : null, "count" : 3 }