1

我需要编写 mongodb 查询,该查询将按数量(订单集合)聚合项目。汇总后或汇总后,应识别库存集合中无法提供的项目,并返回下订单人的姓名

订单代码插入

db.orders.insertMany([
{client:  {firstName: "John",lastName: "Smith" },orderedItems: [{ name: "itemA", qty: 5},{ name: "itemS", qty: 3}]},
{client:  {firstName: "Jan",lastName: "Nowak" },orderedItems: [{ name: "itemA", qty: 56},{ name: "itemS", qty: 53}]},
{client:  {firstName: "Klara",lastName: "Bolączka" },orderedItems: [{ name: "itemA", qty: 35},{ name: "itemS", qty: 23}]},
{client:  {firstName: "Brajan",lastName: "Kowalski" },orderedItems: [{ name: "itemA", qty: 95},{ name: "itemS", qty: 13}]}
]);

股票代码插入

db.stock.insertMany([
{ item: "itemA", qty: 40},
{ item: "itemS", qty: 113}  
]); 

现在我有一些 mongoDB 代码,它只是聚合订单

db.orders.aggregate([
{$unwind: "$orderedItems"},
{$group: { _id: "$orderedItems.name", total:{$sum: "$orderedItems.qty"}}}
]);

我尝试使用查找,但可能我做错了什么。

请给我一些建议好吗?

4

1 回答 1

0

你会喜欢这样的东西吗:

db.orders.aggregate([
{
    $unwind: "$orderedItems" // flatten the "orderedItems" array
},
{
    $group: {
        "_id": "$orderedItems.name", // group by orderItems.name
        "total": {
            $sum: "$orderedItems.qty" // calculate total quantity
        },
        "users": {
            $addToSet: "$client" // create an array of clients who have ordered each item
        }
    }
}, {
    $lookup: { // retrieve the stock information
       from: "stock",
       localField: "_id",
       foreignField: "item",
       as: "stock"
    }
}, {
    $unwind: "$stock" // flatten the result array - should always return only one document, given your data model
}, {
    $addFields: { // add a new field...
        "difference": { // ...called "difference"...
            $subtract: [ "$stock.qty", "$total" ] // ...in which we store the difference between the stock qty and the ordered qty
        }
    }
}, {
    $match: { // only return documents...
        "difference": { // ...where the value for "difference"...
            $lt: 0 // ...is less than zero
        }
    }
}])
于 2017-11-16T22:03:15.980 回答