mongo db aggregate保持组后的字段

时间:2017-09-14 09:26:58

标签: mongodb mongoose aggregation-framework

我有这个聚合:

[
    {
        $match: {_id: new ObjectId('xxx')}
    },
    {
        $unwind: "$users"
    },
    {
        $group: {
            _id: '$users.status',
            count: {$sum: 1}
        }
    },
    {
        $project: {
            name: 1,
            field1: 1,
            field2: 1,
            count: '$count'
        }
    }
]

架构:

{
    name: String,
    field1: String,
    field2: Schema.Types.Mixed,
    users: [{
        user: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        status: String
    }]
}

预期结果:

{
    name: 'NY',
    field1: 'example',
    field2: 'example2',
    statuses: [
        {
            _id: 'ONLINE',
            count: 20
        },
        {
            _id: 'OFFLINE',
            count: 120
        },
        {
            _id: 'OTHER',
            count: 230
        }
    ]
}

这样我只获取用户状态的组结果,而不是原始对象的其他字段。

0 个答案:

没有答案