Yasith Samarawickrama
Yasith Samarawickrama

Reputation: 91

how to get the two collections data into one output in mongodb using node js

These are my two collections in MongoDB, and when I use $lookup to get the details my result comes with a nested array. I need the result to be like below:

First collection

locations = [{
  locationName : "DC",
  locationCategoryCode:"1"
}, {
  locationName : "New York",
  locationCategoryCode:"1"
}, {
  locationName : "Utah",
  locationCategoryCode:"2"
}]

Second collection

locationCategory = [{
  locationCategoryCode:"1",
  locationCategoryName:"history"
}, {
  locationCategoryCode:"2",
  locationCategoryName:"nature"
}]

Result

result = [{
  locationName : "DC",
  locationCategoryName:"history"
}, {
  locationName : "NewYork",
  locationCategoryName:"history"
}]

Any solution for this, please and thank you?

Upvotes: 0

Views: 35

Answers (2)

Joe
Joe

Reputation: 28366

Using aggregation you could:

  • $lookup the category, returning an array
  • $addFields to add the category name to the top level document
  • $project to remove the added array and the location code
db.locations.aggregate([
  {$lookup: {
      from: "locationCategory",
      localField: "locationCategoryCode",
      foreignField: "locationCategoryCode",
      as: "locationCategory"
  }},
  {$addFields: {
      locationCategoryName: {
        $arrayElemAt: ["$locationCategory.locationCategoryName",0]
      }
  }},
  {$project: {
      locationCategory: 0,
      locationCategoryCode: 0
  }}
])

Playground

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48733

You can find the associated locationCategoryName of each location by searching locationCategory using the locationCategoryCode.

const locations = [{
  locationName: "DC",
  locationCategoryCode: "1"
}, {
  locationName: "New York",
  locationCategoryCode: "1"
}, {
  locationName: "Utah",
  locationCategoryCode: "2"
}];

const locationCategory = [{
  locationCategoryCode: "1",
  locationCategoryName: "history"
}, {
  locationCategoryCode: "2",
  locationCategoryName: "nature"
}];

const result = locations
  .map(({ locationName, locationCategoryCode }) => ({
    locationName,
    locationCategoryName: locationCategory.find(({ locationCategoryCode: curr }) =>
      curr === locationCategoryCode).locationCategoryName
  }));

console.log(result);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 0

Related Questions