我正在做一个简单的餐厅应用程序,在购物车模块中构造。
我有来自2个集合的数据,即菜单&;车。
菜单模式:
menus = [
{
"_id": "639ac96eec3db0a1ef2b7490",
"menu_name": "Burger",
"menu_type": "Veg",
"cuisine_type": "American",
"price": 5,
"Quantity": 0
},
{
"_id": "639aca45ec3db0a1ef2b7498",
"menu_name": "Tacos",
"menu_type": "Non-veg",
"cuisine_type": "Mexican",
"price": 3,
"Quantity": 0
},
{
"_id": "639af103eaa2d49802f66b12",
"menu_name": "Pizza",
"menu_type": "Veg",
"cuisine_type": "Italian",
"price": 6,
"Quantity": 0
},
{
"_id": "63a4257efe88505582685fe8",
"menu_name": "Sushi",
"menu_type": "Non-veg",
"cuisine_type": "Japanese",
"price": 4,
"Quantity": 0
},
{
"_id": "63a42592fe88505582685fea",
"menu_name": "Thai Curry",
"menu_type": "Non-veg",
"cuisine_type": "Thai",
"price": 5,
"Quantity": 0
}
];
购物车模式:
cart = [
{
"_id": "63b3cf4c5303f351577fd1b9",
"menuId": "639ac96eec3db0a1ef2b7490",
"menuQuantity": 3
},
{
"_id": "63b67d08b39f6c7eb335aa30",
"menuId": "639af103eaa2d49802f66b12",
"menuQuantity": 1
}
];
如果购物车中存在菜单项,则应更新其数量计数&如果不是,数量应该为零。
预期结果:
result = [
{
"_id": "639ac96eec3db0a1ef2b7490",
"menu_name": "Burger",
"menu_type": "Veg",
"cuisine_type": "American",
"price": 5,
"Quantity": 3
},
{
"_id": "639aca45ec3db0a1ef2b7498",
"menu_name": "Tacos",
"menu_type": "Non-veg",
"cuisine_type": "Mexican",
"price": 3,
"Quantity": 0
},
{
"_id": "639af103eaa2d49802f66b12",
"menu_name": "Pizza",
"menu_type": "Veg",
"cuisine_type": "Italian",
"price": 6,
"Quantity": 1
},
{
"_id": "63a4257efe88505582685fe8",
"menu_name": "Sushi",
"menu_type": "Non-veg",
"cuisine_type": "Japanese",
"price": 4,
"Quantity": 0
},
{
"_id": "63a42592fe88505582685fea",
"menu_name": "Thai Curry",
"menu_type": "Non-veg",
"cuisine_type": "Thai",
"price": 5,
"Quantity": 0
}
]
感谢任何帮助。谢谢!
从$lookup
的结果中先执行$lookup
,再执行$set
。
db.menus.aggregate([
{
"$lookup": {
"from": "cart",
"localField": "_id",
"foreignField": "menuId",
"as": "cartLookup"
}
},
{
$set: {
Quantity: {
$sum: "$cartLookup.menuQuantity"
}
}
},
{
"$unset": "cartLookup"
},
{
"$merge": {
"into": "menus",
"on": "_id",
"whenMatched": "merge"
}
}
])
Mongo操场