MongoDB查找聚合

MongoDB查找聚合,mongodb,nosql,aggregation-framework,Mongodb,Nosql,Aggregation Framework,我有停车收费,比如: parking: { _id: xxxxxx, name: xxxxxx, vehicles: [{vehicleId: xxxxx, bid: xxxxx}...] } 及车辆收集: car: { _id: "xxxx", attributes: [xxxxx], color: "xxxx" } 当我执行查找聚合时: $lookup: { from: "car", localField: "vehicles.veh

我有停车收费,比如:

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...]
}
所以我很难将new cars数组与vehicles数组中匹配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" }
 }}
 ])

通过组合
$reduce
运算符,可以更轻松地使用
$map
运算符

试试这个:

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

|

你能发布汽车采集的样本数据吗?@Valijon I update,basicaly我需要整个汽车来代替车辆字段中每个对象的车辆ID谢谢你,我为此尝试了两条路径,但无法在春季工作投影…聚合.项目()和(“车辆”).嵌套(字段.字段(“车辆.车辆.(U颜色”))请给出无法在子对象中使用虚线字段的错误信息,或者在使用Aggregation.project(“vehicles.vehicle._id”)时出现的错误信息;给我null@UrosKalajdzicSpring data ProjectAggregation很难填充,再次感谢您尝试“丑陋”的手动实现,看起来项目的操作比addFields少。您知道如果我使用addFields,它们之间的性能损失是什么吗?@UrosKalajdzic
$addFields
不会影响性能。正如我所说,Spring
ProjectAggregation
的可用性很低(编写正确的表达式需要太多的脑力劳动),最好实现
toDocument
并直接传递JSON文档。