Hello,
I am new to MongoDB and want to design a database for my small food planning application.
I would like to join them with a lookup, so that ingredients array in meals collection becomes enriched with all the product information.
This is my playground:
Meals collection
{
"_id":{"$oid":"635a732932edf20bed23da5a"},
"name":"Tomato with egg",
"recipe":"Mix tomato with egg.",
"image":"/images/tomatowithegg.png",
"portions":{"$numberDouble":"2.0"},
"ingredients":
[
{"product_id":{"$oid":"635a715b32edf20bed23da54"},
"serving":"tbsp",
"amount":{"$numberDouble":"2.0"}},
{"product_id":{"$oid":"635a71fb32edf20bed23da55"},
"serving":"piece",
"amount":"1"}
]
}
Products collection
{
"_id":{"$oid":"635a715b32edf20bed23da54"},
"name":"Tomato",
"image":"/images/tomato.png",
"nutrients":
{
"kcal":"300",
"carbohydrates":"100",
"fat":"50",
"protein":"2"
},
"servings":
{
"g":"1",
"piece":"200",
"tbsp":"10",
"tsp":"5",
"ml":"1"
}
}
{
"_id":{"$oid":"635a71fb32edf20bed23da55"},
"name":"Egg",
"image":"/images/egg.png",
"nutrients":
{
"kcal":"300",
"carbohydrates":"100",
"fat":"50",
"protein":"2"
},
"servings":
{
"g":"1",
"piece":"200",
"tbsp":"10",
"tsp":"5",
"ml":"1"
}
}
This is my current pipeline, but it results in two arrays - ingredients and products.
[{
$lookup: {
from: 'products',
localField: 'ingredients.product_id',
foreignField: '_id',
as: 'products'
}
}]
Could you please help me with the Lookup?
Also, would there be a way to automatically calculate nutrients for a meal, based on products inside?
Thank you,
Lukas
