I want to know the document size/number when user do the filtering
For example,
- Restaurant A has 5 dishes on the menu
- Restaurant B has 10 dishes on the menu
- Restaurant C has 15 dishes on the menu
Restaurant model:
{
_id: ObjectId("6247bb494c0697948d2813d9"),
restaurant_name: 'A'
}
Dishes model:
{
_id: ObjectId("6247bb484c0697948d280b19"),
dish_name: "Dish A",
restaurant_id: ObjectId("6247bb494c0697948d2813d9")
}
Right now, the user want to do the filtering. He just wants to know which restaurant has more than 10 dishes and show the restaurant and dish info to the customer.
The result should be (only show restaurant B and C because only this two restaurant have more then 10 dish.):
[
{
restaurant_name: 'B',
menu: [
{
dish_name: 'Dish B'
},
{
dish_name: 'Dish C'
}, ....
]
},
{
restuarant_name: 'C'.
menu: [ ..... ]
}
]
CodePudding user response:
Maybe something like this:
db.restaurants.aggregate([
{
"$lookup": {
"from": "dishes",
"localField": "_id",
"foreignField": "restaurant_id",
"as": "menu"
}
},
{
$addFields: {
countDishes: {
$size: "$menu"
}
}
},
{
$match: {
countDishes: {
$gt: 5
}
}
}
])
Explained:
- $lookup/join the resaurant collection with disesh collection in menu
- Add one more field countDishes where you count the dishes per restaurant
- $match the dishes count ( in the example > 5 )