如何通过java驱动程序通过聚合函数(如group,count和distinct)访问mongodb集合?

时间:2012-07-15 22:27:31

标签: java mongodb mongodb-query

这是我的mongdb Collection:

 { "_id" : ObjectId("50033fb1ecc250aa369a678a"), "ID" : 1, "FirstName" : "ijaz",
"LastName" : "alam", "Age" : 21, "Address" : "peshawer" }
{ "_id" : ObjectId("50033fc2ecc250aa369a678b"), "ID" : 2, "FirstName" : "ashfaq"
,"LastName" : "khan", "Age" : 1921, "Address" : "sadkabad" }
{ "_id" : ObjectId("50033fdeecc250aa369a678c"), "ID" : 3, "FirstName" : "danyal"
,"LastName" : "alam", "Age" : 18, "Address" : "lahore" }
{ "_id" : ObjectId("50033ff7ecc250aa369a678d"), "ID" : 43, "FirstName" : "shahzad"
, "LastName" : "sad", "Age" : 22, "Address" : "nazirabad" }

现在我想通过java驱动程序使用集合函数,如group,distinct和count on count集合,或者如何通过java驱动程序在查询中实现聚合函数。

1 个答案:

答案 0 :(得分:3)

Distinctcount以及特殊的Mongo命令,您无需进行任何特殊聚合即可使用这些命令。只需在DBCollection实例上使用适当的参数调用它们。

myCollection.distinct("Age") // gives you all the ages in the collection
myCollection.count(new BasicDBObject("Age", 22)) // gives you a count of 22 year olds

对于其他聚合操作,您需要Java GroupCommand

new GroupCommand(myCollection,
             new BasicDBObject("Age ", true),
             null,
             new BasicDBObject("count", 0),
            "function(key,val){ val.count++;}", 
             null); //gives counts of each age in the collection

如果您正在使用Mongo或更高版本的2.1.x开发版本,请查看聚合框架。它比现有的group命令更好(但在回答时尚未准备好生产)。