在mongodb中以dynamicKey:value格式进行$分组

时间:2017-04-04 12:17:43

标签: mongodb mongodb-query aggregation-framework

大家好我想将mongodb查询结果分组为;

var obj = {dynamicKey: value}

例如,集合就像;

{name: "alex" , age: 21},
{name: "felix" , age: 81},
{name: "hannah" , age: 12}, 
{name: "tom" , age: 18}

我想把收藏品作为;

{alex: 21},
{felix: 81},
{hannah: 12}, 
{tom: 18}

是否可以在$group中使用mongodb执行此操作?

db.collection.aggregate([
    {
        $group : {
            _id: "",
            "$name" : { $first: "$age"}
        }
    }
]).pretty()

但这会引发错误; "errmsg" : "The field name '$name' cannot be an operator name",

我该怎么做?

0 个答案:

没有答案