我想在Mongo shell中运行一个Mongo DB查询。它针对数组的每个元素运行,其中每个元素由participantId
和meal id组成。该查询执行以下操作:
mealPlanPairs = [
{"participantId": "60647d142330a251a859c300", "_id": "640891c8184c7bb950b75407"},
{"participantId": "6065885a5adde01b1ee8a85f", "_id": "640891ac184c7bb950b75406"}
];
// Loop through each pair and perform the update
mealPlanPairs.forEach(function(pair) {db.ParticipantDietMealPlanDetailsDTO.updateOne(
{"participantId": pair.participantId},
{$set: {"mealPlan": db.MasterMealPlanDTO.findOne({"_id": ObjectId(pair._id)}).mealPlan}}
);});
现在在shell中我不能运行这个查询,因为Mongo shell不支持这个。所以目前我通过手动添加id来为每个元素运行这个查询。我如何编写一个遍历数组并做同样事情的查询?
目前我正在手动操作:
db.getCollection('PARTICIPANT_DIET_MEAL_PLAN_DETAILS_PLAN').updateMany(
{"participantId": "5f42698f60bb57ecc2049f8f"},
{$set: {"mealPlan": db.MASTER_MEAL_PLAN.findOne({"_id": "64088fa3184c7bb950b753f6"}).mealPlan}}
)
有没有什么方法可以在一个Mongo DB查询中做到这一点?
1条答案
按热度按时间gg0vcinb1#
mealPlanPairs
数组已定义forEach
循环元素updateOne
(用MasterMealPlanDTO
集合中的相应膳食计划更新ParticipantDietMealPlanDetailsDTO
集合中的字段mealPlan
PS.用数据库中的正确名称替换集合和字段名称