无法根据条件查找子文档计数

时间:2017-12-30 10:10:13

标签: node.js mongodb mongoose

我有一个架构,其中有一些字段.. 我无法找到这个查询,我试过$ group但是找不到结果 收集:任务

{
    "_id" : ObjectId("5a475ee4b342fa03e71192bd"),
    "title" : "Some Title",
    "assignedUsers" : [
        {
            "_id" : ObjectId("5a47386ee4788102e530f60d"),
            "name" : "Sam",
            "status" : "Unconfirmed"
        },
        {
            "_id" : ObjectId("5a473878e4788102e530f60f"),
            "name" : "Ricky",
            "status" : "Rejected"
        }
        {
            "_id" : ObjectId("5a47388be4788102e530f611"),
            "name" : "Niel",
            "status" : "Unconfirmed"
        },
        {
            "_id" : ObjectId("5a47388be4788102e530f611"),
            "name" : "ABC",
            "status" : "Unconfirmed"
        },
        {
            "_id" : ObjectId("5a473892e4788102e530f612"),
            "name" : "Rocky",
            "status" : "Rejected"
        }
    ]
}

结果应该包含 未确认= 3 拒绝= 2

由于

1 个答案:

答案 0 :(得分:1)

使用以下查询,

db.coll3.aggregate([{
            $unwind: '$assignedUsers'
        }, {
            $group: {
                _id: '$assignedUsers.status',
                'count': {
                    $sum: 1
                }
            }
        }
    ])

如果要查询特定文档,请确保使用$ match作为第一阶段,然后使用另外2 $ unwind和$ group。 你会得到结果

{ "_id" : "Rejected", "count" : 2 }
{ "_id" : "Unconfirmed", "count" : 3 }

希望这有帮助。

相关问题