Home > OS >  Finding the product from all shops, that's below the minimum limit in mongodb
Finding the product from all shops, that's below the minimum limit in mongodb

Time:04-04

Make a group by id and get a list of the product are below limit compare to present total stock Id can be same, but name is unique for all id For example, id: 1 and name can be: a, b, c, d.. Means, name will not repeat

My data List:

 const dataList = [
    {
      id: 1,
      name: "a",
      totalQty: 200,
      minimumQty: 100,
    },
    {
      id: 1,
      name: "b",
      totalQty: 90,
      minimumQty: 100,
    },
    {
      id: 1,
      name: "c",
      totalQty: 40,
      minimumQty: 50,
    },
    {
      id: 2,
      name: "a",
      totalQty: 200,
      minimumQty: 100,
    },
    {
      id: 2,
      name: "b",
      totalQty: 90,
      minimumQty: 100,
    },
  ];
  
}

answer

{ result : [
  {
    id: 1,
    belowLimit: [
      { name: "b", totalQty: 90 },
      { name: "c", totalQty: 40 },
    ],
  },
  {
    id: 2,
    belowLimit: [
      { name: "b", totalQty: 90 },
    ],
  },
];}

CodePudding user response:

db.test.aggregate([
{'$match': 
   {'$expr': {'$lt': ['$totalQty', '$minimumQty']}
   }
},
{'$group': 
   {'_id': '$id', 
    'belowLimit': {'$push': {name:'$name', qty:'$totalQty'}}
   }
}])

You could first select only those documents where the quantity is lesser than the required amount and after that you can group by the id of the shop

  • Related