获取Mongodb平均两列的单独结果

时间:2018-02-16 08:31:29

标签: mongodb mongodb-query aggregation-framework

我有一个像t

这样的数据集
{
    "_id" : ObjectId("5a867bae000e4f1c9c77d36d"),
    "userid" : "5a20ee1acdacc7086ce7742d",
    "sprice" : null,
    "lprice" : 4.2,
    "fruit" : "@Apple",
    "createdate" : ISODate("2018-02-16T06:35:26.285Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5a867bae000e4f1c9c77d36e"),
    "userid" : "5a20ee1acdacc7086ce7742e",
    "sprice" : 3.5,
    "lprice" : null,
    "fruit" : "@Apple",
    "createdate" : ISODate("2018-02-16T06:35:26.285Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5a867bae000e4f1c9c77d36e"),
    "userid" : "5a20ee1acdacc7086ce7742e",
    "sprice" : 8.6,
    "lprice" : 2.2,
    "fruit" : "@Apple",
    "createdate" : ISODate("2018-02-16T06:35:26.285Z"),
    "__v" : 0
}

为此,我必须计算'@Apple'的平均值,并忽略那些值为NULL的条目。

对于这个我的查询是这样的,它返回我想要的,即

db.Collection.aggregate([
    { "$match": {
        "fruit": "@Apple",
        "sprice": {$ne:null}
    }},
    { "$group": {
        "_id": null,
        "sprice": { "$avg": "$sprice" }
    }}
])

它给了我结果。现在我的问题是如果我想获得sprice和lprice的个人结果,那么我的查询是如何修改的。

预期答案将是这样的:

{ "_id" : null, "sprice" : 6.05 } // Already Get from this query
{ "_id" : null, "lprice" : 3.2 } //Desired Result.

感谢任何帮助

2 个答案:

答案 0 :(得分:0)

$facet

db.Collection.aggregate([
    { "$match": { "fruit": "@Apple" } },
    {
        "$facet": {
            "sprice": [
                { "$match": { "sprice": { "$ne": null } } },
                { "$group": {
                    "_id": null,
                    "sprice": { "$avg": "$sprice" }
                }}
            ],   
            "lprice": [
                { "$match": { "lprice": { "$ne": null } } },                
                { "$group": {
                    "_id": null,
                    "lprice": { "$avg": "$lprice" }
                }}
            ]
        }
    }
])

示例输出

[
    { "sprice": { "_id" : null, "sprice" : 6.05 } },
    { "lprice": { "_id" : null, "lprice" : 3.2 } }
]

答案 1 :(得分:0)

$avg默认忽略非数字值,因此不需要显式空值过滤器,管道下方会为您提供所需的结果

db.Collection.aggregate([
    { "$match": {
        "fruit": "@Apple"        
    }},
    { "$group": {
        "_id": null,
        "sprice": { "$avg": "$sprice" },
        "lprice": { "$avg": "$lprice" }
    }}       
])