mongodbstudio3t

MongoDB inserting child document on ID reference


I migrated my SQL database into a MongoDB database for a project. It migrated the foreign keys as the ID's that were already there. For example I have these two columns linked through the driversId: enter image description here

My question is how do I get the driver as a document in the driver_standings collection? Thanks in advance!

Edit: I've used the answer below with $merge to update the collection:

db.driverstandings.aggregate([{
  $lookup: {
    from: "drivers",
    localField: "driverId",
    foreignField: "driverId",
    as: "driver"
  }
}, { $merge: { into:"driverstandings" } }
])
    

Solution

  • use $lookup aggregation operator

    db.driver_standings.aggregate([{
      $lookup: {
        from: "drivers",
        localField: "driverId",
        foreignField: "driverId",
        as: "driver"
      }
    }])