使用多维数组进行mongodb聚合

sz81bmfz  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(139)

如果我在多维数组中有索引,我如何聚合两个集合?

//collection 1 item example:
{ 
    _id: ObjectId('000'),
    trips: [ // first array
        { // trip 1
            details: [ // array in first array
                { // detail 1
                    key: ObjectId('111') // ==> _id i want aggregate
                }
            ]
        }
    ]
}

//collection 2 item exampe:
{ 
    _id: ObjectId('111'),
    description: 'any info here...'
}

为了得到一个有效的结果,需要做什么程序呢?2我不想在“查找”之后重新处理每一个数据。
这就是我想要的结果

//collection 1 after aggregate:
{ 
    _id: ObjectId('000'),
    trips: [
        { // trip 1
            details: [
                { // detail 1
                    key: ObjectId('111') // id i want aggregate
                    _description_obj: {
                        _id: ObjectId('111'),
                        description: 'any info here...'
                    }
                }
            ]
        }
    ]
}
ovfsdjhp

ovfsdjhp1#

这里有一个方法可以做到这一点。

db.coll1.aggregate([
  {
    "$match": {
      _id: ObjectId("000000000000000000000000")
    }
  },
  {
    "$lookup": {
      "from": "coll2",
      "localField": "trips.details.key",
      "foreignField": "_id",
      "as": "coll2"
    }
  },
  {
    "$set": {
      "trips": {
        "$map": {
          "input": "$trips",
          "as": "trip",
          "in": {
            "$mergeObjects": [
              "$$trip",
              {
                "details": {
                  "$map": {
                    "input": "$$trip.details",
                    "as": "detail",
                    "in": {
                      "$mergeObjects": [
                        "$$detail",
                        {
                          "_description_obj": {
                            "$first": {
                              "$filter": {
                                "input": "$coll2",
                                "cond": {"$eq": ["$$this._id", "$$detail.key"]}
                              }
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      },
      "coll2": "$$REMOVE"
    }
  }
])

mongoplayground.net上试试。

相关问题