Home > Software design >  how to filter arrays while adding it in mongo view?
how to filter arrays while adding it in mongo view?

Time:10-06

Below is one of the documents in a collection named "hero_foods"

{
    "_id": "Almond Butter",
    "title": "Almond Butter",
    "food_group": "protein",
    "recommendations_group": [
        "DT1",
        "DT2",
        "DT3",
        "DT4"
    ]
}

Below is one of the document in a collection named "recommendation_items"

{
  "_id": "DT1",
  "type": "DIET",
  "title": "pfc",
  "recommendation_items": {
  "title": "What you'll eat",
    "food_groups": [
     {
        "title" : "Quality Carbs",
        "category_id" : "carbs"
     },
     {
        "title" : "Protein",
        "category_id" : "protein"
     },
     {
        "title" : "Healthy Fats",
        "category_id" : "fats"
     }
    ]
  }
}

Below is my Mongo View Create query

database.createView("recommendation_items_view",recommendation_items,
    Arrays.asList(new Document("$match", 
        new Document("type", "DIET")), 
        new Document("$lookup", 
        new Document("from", "hero_foods")
            .append("localField", "_id")
            .append("foreignField", "recommendations_group")
            .append("as", "recommendation_items.hero_foods_list")), 
        new Document("$set", 
        new Document("recommendation_items.food_groups.hero_foods_list", "$recommendation_items.hero_foods_list")), 
        new Document("$project", 
        new Document("recommendation_items.hero_foods_list", 0L))));

This creates a document in view like below,

{
    "_id": "DT1",
    "type": "DIET",
    "title": "pfc",
    "recommendation_items": {
        "title": "What you'll eat",
        "more_options": {
            "title": "Looking for more options?",
            "description": "Tailor your taste by answering our food preferences questionnaire"
        },
        "food_groups": [
            {
                "title": "Quality Carbs",
                "description": "High-quality carbs have essential vitamins, minerals, and nutrients in a natural 'package' that limits fluctuations in blood sugar and insulin that contribute, at least in part, to chronic illness and overeating",
                "image": "image/quality-carbs-thumb_",
                "category_id": "carbs",
                "hero_foods_list": [
                    {
                        "_id": "Almond Butter",
                        "title": "Almond Butter",
                        "short_description": "Almond butter is a food paste made from grinding almonds into a nut butter.",
                        "image_thumb": "/images/diet-almond-butter-thumb_",
                        "image_banner": "/images/diet-almond-butter-banner_",
                        "long_description": "Almond butter is a food paste made from grinding almonds into a nut butter. Almond butter may be crunchy or smooth, and is generally stir or no-stir Almond butter may be either raw or roasted, but this describes the almonds themselves, prior to grinding.",
                        "food_group": "protein",
                        "recommendations_group": [
                            "DT1",
                            "DT2",
                            "DT3",
                            "DT4"
                        ],
                        "disliked_food_categories": [
                            "tree_nuts"
                        ],
                        "eating_patterns": [
                            "vegetarian",
                            "plant_based"
                        ],
                        "eating_practices": [
                            "kosher",
                            "halal"
                        ]
                    }
                ]
            },
            {
                "title": "Protein",
                "description": "any of a class of nitrogenous organic compounds which have large molecules composed of one or more long chains of amino acids and are an essential part of all living organisms, especially as structural components of body tissues such as muscle, hair, etc., and as enzymes and antibodies.",
                "image": "image/protein-thumb_",
                "category_id": "protein",
                "hero_foods_list": [
                    {
                        "_id": "Almond Butter",
                        "title": "Almond Butter",
                        "short_description": "Almond butter is a food paste made from grinding almonds into a nut butter.",
                        "image_thumb": "/images/diet-almond-butter-thumb_",
                        "image_banner": "/images/diet-almond-butter-banner_",
                        "long_description": "Almond butter is a food paste made from grinding almonds into a nut butter. Almond butter may be crunchy or smooth, and is generally stir or no-stir Almond butter may be either raw or roasted, but this describes the almonds themselves, prior to grinding.",
                        "food_group": "protein",
                        "recommendations_group": [
                            "DT1",
                            "DT2",
                            "DT3",
                            "DT4"
                        ],
                        "disliked_food_categories": [
                            "tree_nuts"
                        ],
                        "eating_patterns": [
                            "vegetarian",
                            "plant_based"
                        ],
                        "eating_practices": [
                            "kosher",
                            "halal"
                        ]
                    }
                ]
            },
            {
                "title": "Healthy Fats",
                "description": "Monounsaturated fats and polyunsaturated fats are known as the “good fats” because they are good for your heart, your cholesterol, and your overall health. These fats can help to: Lower the risk of heart disease and stroke.",
                "image": "image/healthy-fats-thumb_",
                "category_id": "fats",
                "hero_foods_list": [
                    {
                        "_id": "Almond Butter",
                        "title": "Almond Butter",
                        "short_description": "Almond butter is a food paste made from grinding almonds into a nut butter.",
                        "image_thumb": "/images/diet-almond-butter-thumb_",
                        "image_banner": "/images/diet-almond-butter-banner_",
                        "long_description": "Almond butter is a food paste made from grinding almonds into a nut butter. Almond butter may be crunchy or smooth, and is generally stir or no-stir Almond butter may be either raw or roasted, but this describes the almonds themselves, prior to grinding.",
                        "food_group": "protein",
                        "recommendations_group": [
                            "DT1",
                            "DT2",
                            "DT3",
                            "DT4"
                        ],
                        "disliked_food_categories": [
                            "tree_nuts"
                        ],
                        "eating_patterns": [
                            "vegetarian",
                            "plant_based"
                        ],
                        "eating_practices": [
                            "kosher",
                            "halal"
                        ]
                    }
                ]
            }
        ]
    }
}

I want to add recommendation_items.food_groups.hero_foods_list in respective recommendation_items.food_groups with following condition,

i.e i want data in recommendation_items.food_groups.hero_foods_list of "food_group-protein" only in food_groups of "protein" as shown below

**

**{
    "_id": "DT1",
    "type": "DIET",
    "title": "pfc",
    "recommendation_items": {
        "title": "What you'll eat",
        "more_options": {
            "title": "Looking for more options?",
            "description": "Tailor your taste by answering our food preferences questionnaire"
        },
        "food_groups": [
            {
                "title": "Quality Carbs",
                "description": "High-quality carbs have essential vitamins, minerals, and nutrients in a natural 'package' that limits fluctuations in blood sugar and insulin that contribute, at least in part, to chronic illness and overeating",
                "image": "image/quality-carbs-thumb_",
                "category_id": "carbs",
                "hero_foods_list": []
            },
            {
                "title": "Protein",
                "description": "any of a class of nitrogenous organic compounds which have large molecules composed of one or more long chains of amino acids and are an essential part of all living organisms, especially as structural components of body tissues such as muscle, hair, etc., and as enzymes and antibodies.",
                "image": "image/protein-thumb_",
                "category_id": "protein",
                "hero_foods_list": [
                    {
                        "_id": "Almond Butter",
                        "title": "Almond Butter",
                        "short_description": "Almond butter is a food paste made from grinding almonds into a nut butter.",
                        "image_thumb": "/images/diet-almond-butter-thumb_",
                        "image_banner": "/images/diet-almond-butter-banner_",
                        "long_description": "Almond butter is a food paste made from grinding almonds into a nut butter. Almond butter may be crunchy or smooth, and is generally stir or no-stir Almond butter may be either raw or roasted, but this describes the almonds themselves, prior to grinding.",
                        "food_group": "protein",
                        "recommendations_group": [
                            "DT1",
                            "DT2",
                            "DT3",
                            "DT4"
                        ],
                        "disliked_food_categories": [
                            "tree_nuts"
                        ],
                        "eating_patterns": [
                            "vegetarian",
                            "plant_based"
                        ],
                        "eating_practices": [
                            "kosher",
                            "halal"
                        ]
                    }
                ]
            },
            {
                "title": "Healthy Fats",
                "description": "Monounsaturated fats and polyunsaturated fats are known as the “good fats” because they are good for your heart, your cholesterol, and your overall health. These fats can help to: Lower the risk of heart disease and stroke.",
                "image": "image/healthy-fats-thumb_",
                "category_id": "fats",
                "hero_foods_list": []
            }
        ]
    }
}**

**

CodePudding user response:

I think one solution is this one:

db.recommendation_items.aggregate([
   { $match: { type: "DIET" } },
   {
      $lookup: {
         from: "hero_foods",
         localField: "_id",
         foreignField: "recommendations_group",
         as: "recommendation_items.hero_foods_list"
      }
   },
   {
      $set: {
         "recommendation_items.food_groups": {
            $map: {
               input: "$recommendation_items.food_groups",
               as: "foodGroup",
               in: {
                  $mergeObjects: [
                     "$$foodGroup",
                     {
                        hero_foods_list: {
                           $filter: {
                              input: "$recommendation_items.hero_foods_list",
                              as: "heroFood",
                              cond: { $eq: ["$$foodGroup.category_id", "$$heroFood.food_group"] }
                           }
                        }
                     }
                  ]
               }
            }
         }
      }
   }
])

See Mongo playground

  • Related