#mongodb #mongodb-query
Вопрос:
Ниже приведен один из документов в коллекции под названием «hero_foods».
{
"_id": "Almond Butter",
"title": "Almond Butter",
"food_group": "protein",
"recommendations_group": [
"DT1",
"DT2",
"DT3",
"DT4"
]
}
Ниже приведен один из документов в коллекции под названием «рекомендация_итемы».
{
"_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"
}
]
}
}
Ниже приведен мой запрос на создание представления Монго
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))));
Это создает документ в представлении, как показано ниже,
{
"_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"
]
}
]
}
]
}
}
Я хочу добавить recommendation_items.food_groups.hero_foods_list
в соответствии recommendation_items.food_groups
со следующим условием,
т. е. мне нужны данные в recommendation_items.food_groups.hero_foods_list
«food_group-белок» только в food_groups
«белке», как показано ниже
**
**{
"_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": []
}
]
}
}**
**
Комментарии:
1. Не могли бы вы, пожалуйста, поместить образец выходного документа. И, пожалуйста, удалите поля, которые не имеют отношения к вашей проблеме!
2. Пример вывода представления содержится в самом вопросе в последнем.
3. @WernfriedDomscheit Я удалил поля, которые не имеют отношения к моей проблеме
4. Я удаляю дополнительные элементы, которые я не вижу актуальной для вас проблемы. Итак, какого результата вы ожидаете?
5. @WernfriedDomscheit Я хочу добавить recommendation_items.food_groups.hero_foods_list в соответствующие recommendation_items.food_groups со следующим условием: «$recommendation_items.food_groups.category_id» $eq «$recommendation_items.food_groups.hero_foods_list.food_group»
Ответ №1:
Я думаю, что одно из решений заключается в следующем:
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"] }
}
}
}
]
}
}
}
}
}
])
Увидеть детскую площадку Монго
Комментарии:
1. Большое спасибо, сэр. Это сработало. Спасибо, я застрял в этом на 2 дня. Это решение должно было меня поразить