Count Elements SubDocument that match a given criterion

吃可爱长大的小学妹 提交于 2019-12-20 07:12:43

问题


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?


回答1:


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 }



回答2:


As per question it looks like you want to find out where group array last_read contains null. For this you use $in in aggregation and then unwind personal array and count the array. Check bellow aggregation query

db.collection.aggregate({
    "$match": {
        "conversations.group.last_read": {
            "$in": [null]
        }
    }
}, {
    "$unwind": "$conversations.personal"
}, {
    "$group": {
        "_id": "$_id",
        "personalArrayCount": {
            "$sum": 1
        }
    }
})


来源:https://stackoverflow.com/questions/39620555/count-elements-subdocument-that-match-a-given-criterion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!