提问者:小点点

如何在MongoDB的嵌入式文档中计算每个_id


我的文件看起来像:

_id: 1,
    chat: [
    {
     sender: "michael",
     message: "hello",
     status: "pending",
     receiver: "jennifer"
    },
    {
     sender: "michael",
     message: "how are you ?",
     status: "sent",
     receiver: "jennifer"
    }
    ]
_id: 2,
    chat: [
    {
     sender: "michael",
     message: "hello",
     status: "pending",
     receiver: "bobby"
    },
    {
     sender: "michael",
     message: "how are you ?",
     status: "pending",
     receiver: "bobby"
    }
    ]

如何从嵌入文档中获取status="pending"的计数?我希望结果如下所示:

_id: 1,
sender: "michael",
receiver: "jennifer",
status_pending: 1
_id: 2,
sender: "michael",
receiver: "bobby",
status_pending: 2,

我不知道如何在MongoDB中使用$unstyle、$group、$size。请有人帮我…


共1个答案

匿名用户

您可以首先$un转聊天,然后$group通过id、发送者和接收者并使用$sum计数,然后$project返回最终结果。

db.collection.aggregate([
    {$unwind: '$chat'},
    {$match: {'chat.status': 'pending'}},
    {$group: {
        _id: {_id: '$_id', sender: '$chat.sender',receiver: '$chat.receiver'},
        status_pending: {$sum: 1}
    }},
    {$project: {
        _id: '$_id._id', 
        sender: '$_id.sender', 
        receiver: '$_id.receiver', 
        status_pending: 1
    }}
])

最终结果

[{"status_pending":2,"_id":2,"sender":"michael","receiver":"bobby"},{"status_pending":1,"_id":1,"sender":"michael","receiver":"jennifer"}]