从所有商店中查找低于 mongodb 中的最低限制的产品

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

按 id 分组并获得与当前总库存相比低于限制的产品列表 id 可以相同,但 name 对于所有 id 都是唯一的 比如id:1 name可以是:a,b,c,d.. 意思是name不会重复

我的数据列表:

 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,
    },
  ];
  
}

回答

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

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

您可以先select仅那些数量少于要求数量的文件,然后您可以按店铺编号分组