如何在MongoDB的聚合查询中将数组转换为不带键的对象?

时间:2020-04-02 13:34:18

标签: mongodb mongodb-query aggregation-framework

我有这样的查询结果;

{
    "content" : [
        "X",
        "1"
    ]
}

我的查询就是这样;

db.getCollection("x").aggregate([
{$group : {_id : null, tN: {$addToSet : { content: [ "$tN", "$pC" ] }}}},
{$unwind: "$tN"},
{$replaceRoot: {newRoot: '$tN'}}
])

如何将 content 数组转换为

{
    "tN" : "X",
    "pC" : "1"
}

1 个答案:

答案 0 :(得分:0)

您可以在$arrayElemAt阶段使用$project来获得它

db.getCollection("x").aggregate([
  {
    $group: {
      _id: null,
      tN: { $addToSet: { content: [ "$tN", "$pC" ] } }
    }
  },
  {
    $unwind: "$tN"
  },
  {
    $replaceRoot: { newRoot: "$tN" }
  },
  {
    $project: {
      _id: 0,
      "tN": {
        $arrayElemAt: [ "$content", 0 ]
      },
      "pC": {
        $arrayElemAt: [ "$content", 1 ]
      }
    }
  }
])

MongoPlayground