首页 > 解决方案 > MongoDB 查找聚合

问题描述

我有像这样的停车收藏:

parking: {
   _id: xxxxxx,
   name: xxxxxx,
   vehicles: [{vehicleId: xxxxx, bid: xxxxx}...]
}

和汽车收藏:

car: {
  _id: "xxxx",
  attributes: [xxxxx],
  color: "xxxx"
}

当我进行查找聚合时:

  $lookup: {
     from: "car",
     localField: "vehicles.vehicleId",
     foreignField: "_id",  
     as: "cars"
  }

我得到:

parking: {
   _id: xxxxxx,
   name: xxxxxx,
   vehicles: [{vehicleId: xxxxx, bid: xxxxx}],
   cars: [car1,car2...]
}

因此,我很难将新车阵列与车辆阵列中匹配 id 的对象合并。我可以用匹配的汽车文件以某种方式替换 vehicleId 吗?

我试过这个,但组操作从停车场中删除名称字段

 db.parking.aggregate([
 { "$unwind": "$vehicles" },
 { "$lookup": {
   "from": "car",
   "as": "vehicles.vehicle",
   "localField": "vehicles.vehicleId",
   "foreignField": "_id"
 }},
 { "$unwind": "$vehicles.vehicle" },
 { "$group": {
   "_id": "$_id",
   "vehicles": { "$push": "$vehicles" }
 }}
 ])

标签: mongodbnosqlaggregation-framework

解决方案


$map通过组合运算符更容易使用运算$reduce符。

试试这个:

db.parking.aggregate([
  {
    "$lookup": {
      "from": "car",
      "localField": "vehicles.vehicleId",
      "foreignField": "_id",
      "as": "cars"
    }
  },
  {
    $addFields: {
      vehicles: {
        $map: {
          input: "$vehicles",
          as: "veh",
          in: {
            bid: "$$veh.bid",
            vehicleId: {
              $reduce: {
                input: "$cars",
                initialValue: "$$veh.vehicleId",
                in: {
                  $cond: [
                    {
                      $eq: [ "$$this._id", "$$veh.vehicleId" ]
                    },
                    "$$this",
                    "$$value"
                  ]
                }
              }
            }
          }
        }
      },
      cars: "$$REMOVE"
    }
  }
])

Mongo游乐场| 替换车辆ID


推荐阅读