urosbelov
urosbelov

Reputation: 349

MongoDB Lookup Aggregation that better uses $map operator

I have Parking collection like:

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

and car collection:

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

When I do Lookup Aggregation:

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

I get:

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

So I struggle with merging new cars array with objects in vehicles array that match id. Can I somehow replace vehicleId with car document that match?

I tried this but group operation remove name field from parking

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

Upvotes: 0

Views: 124

Answers (1)

Valijon
Valijon

Reputation: 13103

It's easier use $map operator by combining the $reduce operator.

Try this one:

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

MongoPlayground | Replace vehicleId

Upvotes: 1

Related Questions