我是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代码。
提前感谢
问候
让我们试着分解这个问题。我会从开始
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"}}});
尝试获取mongodb的java驱动程序。我可以从mongodb网站获得这个链接。请检查:http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/#java-驱动程序和聚合框架