繁体   English   中英

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

[英]How to convert array to object without keys on aggregation query of MongoDB?

我有这样的查询结果;

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

我的查询就是这样;

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

如何将该内容数组转换为;

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

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

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 ]
      }
    }
  }
])

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM