1

我是 MongoDB 的新手。我必须在 Mongo DB 中找到数组元素的平均值,例如

{
"_id" : ObjectId("51236fbc3004f02f87c62e8e"),
"query" : "iPad",
"rating" : [
    {
        "end" : "130",
        "inq" : "403",
        "executionTime" : "2013-02-19T12:27:40Z"
    },
    {
        "end" : "152",
        "inq" : "123",
        "executionTime" : "2013-02-19T12:35:28Z"
    }
]
}

我想要查询的“inq”平均值:iPad

这里的输出应该是:

inq=263

我在谷歌搜索并得到aggregate method但无法将其转换为 java 代码。

提前致谢

问候

4

2 回答 2

4

让我们尝试分解这个问题。我将从:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0,
q:"$query",i:"$rating.inq"}})

投影不是必需的,但使其余部分更具可读性:

{
    "result" : [
            {
                    "q" : "iPad",
                    "i" : "403"
            },
            {
                    "q" : "iPad",
                    "i" : "123"
            }
    ],
    "ok" : 1
}

那么我该如何分组呢?当然,通过“$q”:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0, 
q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q"}}) :

{ "result" : [ { "_id" : "iPad" } ], "ok" : 1 }

现在让我们添加一些聚合运算符:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project: {_id:0, q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q", max: {$max: "$i"}, min: {$min: "$i"}}}) :

{
    "result" : [
            {
                    "_id" : "iPad",
                    "max" : "403",
                    "min" : "123"
            }
    ],
    "ok" : 1
}

现在是平均值:

db.c.aggregate({$match: {query: "iPad"}}, {$unwind:"$rating"}, {$project:  
{_id:0,q:"$query",i:"$rating.inq"}}, {$group:{_id: "$q", av: {$avg:"$i"}}});
于 2013-02-23T05:52:08.613 回答
0

尝试获取 mongodb 的 java 驱动程序。我可以从 mongodb 站点获取此链接。请检查:http ://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/#java-driver-and-aggregation-framework

于 2013-02-20T07:37:43.640 回答