将静态字段添加到Mongodb中的分组数据

时间:2015-07-02 05:17:59

标签: mongodb

如何使用mongodb中的组操作将静态字段添加到结果中。我的查询如下:

db.sales.aggregate({
    $group : {
        _id: {
            year: { $year: '$date' },
        },
        amount: { $sum: 1 }
    }
});

比得到结果:

{
    "result" : [
        {
            "_id" : {
                "year" : 2013
            },
            "amount" : 43433
        },
        ...
    ]
    "ok" : 1
}

我需要在结果的每个对象中添加名为type且值为'year'的字段。

2 个答案:

答案 0 :(得分:0)

我只需要用文字'year'添加项目操作。查询看起来像:

db.sales.aggregate([
{
    $group : {
        _id: {
            year: { $year: '$registrationDate' }
        },
        amount: { $sum: 1 }
    },
},
{

        $project: {
                type: { $literal: 'year' },

        }    
}

]);

答案 1 :(得分:0)

$ addFields在版本3.4+中可用,例如

db.sales.aggregate({
    $group : {
        _id: {
            year: { $year: '$date' },
        },
        amount: { $sum: 1 }
    },
    {
        $addFields: {
            type: 'year'
        }
    }
});