Joining two collections and possibly calculating totals

@Pavel_Duchovny thank you very much for these!

I still wonder how to apply this into my scenario, where I believe we have a Many-To-Many case. In my app, product may be in many meals and a meal may be made of many products.

I already did embed ingredients - in the beginning I wanted to have three collections - products, ingredients and meals. An ingredient is a product with a serving and quantity. Products to Ingredients would be one to many relationship and ingredients to meals would be one-to-one. That’s why I embedded ingredients inside meals. I still have a problem with products though.

I would love to try embedding, but I still don’t understand how can I reuse the same product in many meals.

This is my current example. I would love to end up with my products embedded inside meals, but one product can appear in many meals and meals have many products.

meal


{
   _id: ObjectId("meal1"),
   ingredients: 
   [
       {
           product_id: ObjectId("AAA"),
           serving: "piece"
           quantity: "1"
       },
       {
           product_id: ObjectId("BBB"),
           serving: "tbsp"
           quantity: "3"
       },
   ]
}

products

{
    {
       _id: ObjectId("AAA"),
      nutrients :
       {
           kcal: "100"
           carbohydrates: "50"
           fat: "10"
           protein: "2"
       },
      servings:
       {
           g: "1"
           tbsp: "10" 
           piece: "30"
           ml: "1"
       },
    },
    {
       _id: ObjectId("BBB"),
      nutrients :
       {
           kcal: "50"
           carbohydrates: "40"
           fat: "5"
           protein: "5"
       },
      servings:
       {
           g: "1"
           tbsp: "15" 
           piece: "300"
           ml: "1"
       },
    },
}

Thank you,
Lukas