Home > other >  Join two collection into one and get the single value from the array
Join two collection into one and get the single value from the array

Time:07-25

How do I join two collections? Let's say

First collection: Name

{
    "First_Name" : "Smith",
    "Last_Name": "Smiths"
}

Second collection: Information

{
    "Last_Name": "Smiths",
    "Address": "Some street"
}

This is what I have so far

db.Name.aggregate([{
    $lookup: {
            from: "Information",
            localField: "Last_Name",
            foreignField: "Last_Name",
            as: "Without_array"
        }
}])

but I need the output to be

{
    "First_Name" : "Smith",
    "Last_Name": "Smiths",
    "Address": "Some street"
}

instead of the array that I get in the end, which I called Without_array.

CodePudding user response:

As mentioned in the comment, you need a $project stage.

Take the first value of the Without_array.Address array via $first.

db.Name.aggregate([
  {
    $lookup: {
      from: "Information",
      localField: "Last_Name",
      foreignField: "Last_Name",
      as: "Without_array"
    }
  },
  {
    $project: {
      First_Name: 1,
      Last_Name: 1,
      Address: {
        $first: "$Without_array.Address"
      }
    }
  }
])

Sample Mongo Playground

  • Related