0

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?

4

2 回答 2

1

以下查询计算子文档的数量personalgroup具有last_readvalue的数组null

$concatArrays将多个数组组合成一个数组。它是在 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}}}
                ])

样本结果:

{ "_id" : null, "count" : 3 }
于 2016-09-21T17:15:00.573 回答
0

根据问题,您似乎想找出group array last_read包含的位置null。为此,您$in在聚合中使用,然后unwind personal对数组进行数组和计数。检查下面的聚合查询

db.collection.aggregate({
    "$match": {
        "conversations.group.last_read": {
            "$in": [null]
        }
    }
}, {
    "$unwind": "$conversations.personal"
}, {
    "$group": {
        "_id": "$_id",
        "personalArrayCount": {
            "$sum": 1
        }
    }
})
于 2016-09-21T16:04:15.217 回答