如何平均mongodb中的汇总值? [英] How to average the summed up values in mongodb?

查看:51
本文介绍了如何平均mongodb中的汇总值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 MongoDB 2.4.8,

Using MongoDB 2.4.8,

我有以下记录

{
    "category" : "TOYS",
    "price" : 12,
    "status" : "online",
    "_id" : "35043"
}
{
    "category" : "TOYS",
    "price" : 13,
    "status" : "offline",
    "_id" : "35044"
}
{
    "category" : "TOYS",
    "price" : 22,
    "status" : "online",
    "_id" : "35045"
}
{
    "category" : "BOOKS",
    "price" : 13,
    "status" : "offline",
    "_id" : "35046"
}
{
    "category" : "BOOKS",
    "price" : 17,
    "status" : "online",
    "_id" : "35047"
}

我想找到状态为在线且总价超过50的每个类别的平均价格.

I want to find the average price of each category whose status is online and total price is more than 50.

我不知道如何构造这个查询.

I am not sure how to construct this query.

到目前为止,我可以构建我总结的查询,并找出状态为在线的每个类别的总价格.

So far, I can construct the query where I summed up and find out the total price for each category whose status is online.

db.products.aggregate([
    {"$match":
        {           
            {status:"online"}
        }
    },
    {"$group" :
        {
            "_id": "$category",
            "total_price": {$sum:"$price"},
        }
    }
])

我不确定如何向此查询添加更多阶段以获得我正在寻找的平均值.

I am not sure how to add more stages to this query to get the averages I am looking for.

推荐答案

您可以向聚合管道添加更多阶段.例如:

You can just add more stages to your aggregation pipeline. For example:

db.items.aggregate([
    {$match:
        {           
            status:"online"
        }
    },
    {$group :
        {
            _id: "$category",
            total_price: {$sum:"$price"},
        }
    },
    {$match:
        {           
            total_price:{$gt:50}
        }
    },
    {$group :
        {
            _id: "1",
            avg_price: {$avg:"$total_price"},
        }
    },
]);

根据说明进行编辑

这篇关于如何平均mongodb中的汇总值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆