如何使用mongodb查找组并计算总数

时间:2017-11-08 18:23:04

标签: mongodb aggregation-framework

我有两个收藏品

1.Product collection ==>

/* 1 */
{
    "_id" : 154,
    "name" : "Chocolate Heaven",
    "price" : 7
}

/* 2 */
{
    "_id" : 155,
    "name" : "Tasty Lemons",
    "price" : 8
}

/* 3 */
{
    "_id" : 156,
    "name" : "Vanilla Dreams",
    "price" : 9
}

2.订单收集==>

/* 1 */
{
    "_id" : 1,
    "product_id" : 154,
    "quantity" : 10
}

/* 2 */
{
    "_id" : 2,
    "product_id" : 155,
    "quantity" : 3
}

/* 3 */
{
    "_id" : 3,
    "product_id" : 156,
    "quantity" : 6
}

/* 4 */
{
    "_id" : 4,
    "product_id" : 154,
    "quantity" : 1
}

我期待产品的出货量是使用mongodb的总价格

156 Vanilla Dreams 9 6 54

db.getCollection('order').aggregate([
        {$group : {_id :{ product_id : "$product_id"}, sellCount : { $sum : "$quantity"}}},
        {$lookup : { from : 'product',localField : '_id.product_id' , foreignField :'_id',as: 'prodDetails' }},
        {$match: {prodDetails: {$ne: []}}}
]);
  1. 你能帮我找出正确的查询。
  2. 如何为此输出创建视图

1 个答案:

答案 0 :(得分:0)

您可以尝试运行仅使用两个步骤 $lookup $addFields 的管道,如下所示:

db.product.aggregate([
    {
        "$lookup": {
            "from": "order",
            "localField": "_id",
            "foreignField": "product_id",
            "as": "orders"
        }
    },
    {
        "$addFields": {
            "total": {
                "$multiply": [
                    "$price",
                    { "$sum": "$orders.quantity" }
                ]
            }
        }
    }
])