计算符合给定标准的元素子文档

Count Elements SubDocument that match a given criterion

我在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
                    }
                    ...
            ]
    }
}

我想计算子数组 personalgrouplast_read 为空的给定用户的对话数。请问我怎样才能做到这一点?

我试过:

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

但没有得到他想要的输出。请问有什么更好的主意吗?

根据问题,您似乎想找出 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
        }
    }
})

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

$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 }