MongoDB聚合,表格类型结果

时间:2019-06-14 04:27:42

标签: mongodb aggregation-framework

我有一个看起来像这样的文档模型

{
    _id: objectId,
    per: [{
        _pid: objectId,
        thing1: sting,
        thing2: string
    }],
    ore: [{
        _oid: objectId,
        thing1: sting,
        thing2: string
    }],
    tre: [{
        _tid: objectId,
        thing1: sting,
        thing2: string
    }]
}

我想拉回表格表示形式

[
    {_id,_pid,thing1,thing2},
    {_id,_pid,thing1,thing2},
    {_id,_oid,thing1,thing2},
    {_id,_oid,thing1,thing2},
    {_id,_oid,thing1,thing2},
    {_id,_tid,thing1,thing2}
]

我将如何去做-我确定这是一个聚合的事情

1 个答案:

答案 0 :(得分:1)

聚合中的

$setUnion可让您将多个数组组合为一个:

MongoPlayground现场观看

db.collection.aggregate([
  { $group: {
     _id: "$_id",
     array: { $push: {
          $setUnion: [
            "$per",
            "$ore",
            "$tre"
          ]
        }
      }
    }
  }
]

从那时起,它只是使结果符合您的喜好。

以下是已完成的示例,其中包含所有待解决的问题:https://mongoplayground.net/p/Z9-HHMoQOPA