将值转换为键mongodb聚合

时间:2019-03-19 09:49:28

标签: mongodb mongodb-query aggregation-framework

以下是聚合查询的结果:

[
    {
         "_id": "5a9433fee5878a000f7cba09",
         "trendingStats": {
            "trendingArr": [],
            "trendingScore": 0
         }
    },
   {
       "_id": "5a942f79e5878a000f7cba06",
       "trendingStats": {
          "trendingArr": [],
          "trendingScore": 0
       }
   }
]

这是查询:

collection.aggregate([
    {$project:{
         'trendingStats':{
           '$ifNull':['$trendingStats',{'trendingArr':[],'trendingScore':0}
         }
    }
]);

我希望结果是一个具有以下格式的文档:

{'5a9433fee5878a000f7cba09':{'trendingArr':[],trendingStats:0},
 '5a942f79e5878a000f7cba06':{'trendingArr':[],trendingStats:0},
}

有没有办法将结果转换成一个文档?

1 个答案:

答案 0 :(得分:3)

您可以在$project

之后的以下阶段使用
{ "$group": {
  "_id": null,
  "data": {
    "$push": {
      "k": { "$toString": "$_id" },
      "v": "$trendingStats"
    }
  }
}},
{ "$replaceRoot": {
  "newRoot": { "$arrayToObject": "$data" }
}}

Output

[
  {
    "5a942f79e5878a000f7cba06": {
      "trendingArr": [],
      "trendingScore": 0
    },
    "5a9433fee5878a000f7cba09": {
      "trendingArr": [],
      "trendingScore": 0
    }
  }
]