Mongodb 聚合查找大小
Mongodb aggregate lookup with size
我想在用户进行过滤时知道文档size/number
例如,
- 餐厅 A 的菜单上有 5 道菜
- 餐厅 B 的菜单上有 10 道菜
- C 餐厅的菜单上有 15 道菜
餐厅型号:
{
_id: ObjectId("6247bb494c0697948d2813d9"),
restaurant_name: 'A'
}
餐具型号:
{
_id: ObjectId("6247bb484c0697948d280b19"),
dish_name: "Dish A",
restaurant_id: ObjectId("6247bb494c0697948d2813d9")
}
现在,用户想要进行过滤。他只想知道哪家餐厅的菜品多于10道菜,然后把餐厅和菜品信息展示给顾客。
结果应该是(只显示餐厅B和C,因为只有这两家餐厅有10多道菜。):
[
{
restaurant_name: 'B',
menu: [
{
dish_name: 'Dish B'
},
{
dish_name: 'Dish C'
}, ....
]
},
{
restuarant_name: 'C'.
menu: [ ..... ]
}
]
也许是这样的:
db.restaurants.aggregate([
{
"$lookup": {
"from": "dishes",
"localField": "_id",
"foreignField": "restaurant_id",
"as": "menu"
}
},
{
$addFields: {
countDishes: {
$size: "$menu"
}
}
},
{
$match: {
countDishes: {
$gt: 5
}
}
}
])
解释:
- $lookup/join 菜单中有菜品集合的餐厅集合
- 再添加一个字段 countDishes,您可以在其中计算每家餐厅的菜肴
- $匹配菜肴数量(在示例中 > 5)
我想在用户进行过滤时知道文档size/number
例如,
- 餐厅 A 的菜单上有 5 道菜
- 餐厅 B 的菜单上有 10 道菜
- C 餐厅的菜单上有 15 道菜
餐厅型号:
{
_id: ObjectId("6247bb494c0697948d2813d9"),
restaurant_name: 'A'
}
餐具型号:
{
_id: ObjectId("6247bb484c0697948d280b19"),
dish_name: "Dish A",
restaurant_id: ObjectId("6247bb494c0697948d2813d9")
}
现在,用户想要进行过滤。他只想知道哪家餐厅的菜品多于10道菜,然后把餐厅和菜品信息展示给顾客。
结果应该是(只显示餐厅B和C,因为只有这两家餐厅有10多道菜。):
[
{
restaurant_name: 'B',
menu: [
{
dish_name: 'Dish B'
},
{
dish_name: 'Dish C'
}, ....
]
},
{
restuarant_name: 'C'.
menu: [ ..... ]
}
]
也许是这样的:
db.restaurants.aggregate([
{
"$lookup": {
"from": "dishes",
"localField": "_id",
"foreignField": "restaurant_id",
"as": "menu"
}
},
{
$addFields: {
countDishes: {
$size: "$menu"
}
}
},
{
$match: {
countDishes: {
$gt: 5
}
}
}
])
解释:
- $lookup/join 菜单中有菜品集合的餐厅集合
- 再添加一个字段 countDishes,您可以在其中计算每家餐厅的菜肴
- $匹配菜肴数量(在示例中 > 5)