Reputation: 91
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:
locations = [{
locationName : "DC",
locationCategoryCode:"1"
}, {
locationName : "New York",
locationCategoryCode:"1"
}, {
locationName : "Utah",
locationCategoryCode:"2"
}]
locationCategory = [{
locationCategoryCode:"1",
locationCategoryName:"history"
}, {
locationCategoryCode:"2",
locationCategoryName:"nature"
}]
result = [{
locationName : "DC",
locationCategoryName:"history"
}, {
locationName : "NewYork",
locationCategoryName:"history"
}]
Any solution for this, please and thank you?
Upvotes: 0
Views: 35
Reputation: 28366
Using aggregation you could:
db.locations.aggregate([
{$lookup: {
from: "locationCategory",
localField: "locationCategoryCode",
foreignField: "locationCategoryCode",
as: "locationCategory"
}},
{$addFields: {
locationCategoryName: {
$arrayElemAt: ["$locationCategory.locationCategoryName",0]
}
}},
{$project: {
locationCategory: 0,
locationCategoryCode: 0
}}
])
Upvotes: 1
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