Home > Back-end >  Mongodb aggregate lookup with size
Mongodb aggregate lookup with size

Time:04-03

I want to know the document size/number when user do the filtering

For example,

  1. Restaurant A has 5 dishes on the menu
  2. Restaurant B has 10 dishes on the menu
  3. 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:

  1. $lookup/join the resaurant collection with disesh collection in menu
  2. Add one more field countDishes where you count the dishes per restaurant
  3. $match the dishes count ( in the example > 5 )

playground

  • Related