简体   繁体   中英

How to acces mongodb collection through aggregate function (like group, count and distinct) through java driver?

Here is my 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" }

Now i want to use aggregate function like group,distinct and count on above collection through java driver or how to implement aggregate functions in query through java driver.

Distinct and count and special Mongo commands, you don't need to do any special aggregation to use those. Just call them with the appropriate parameters on you DBCollection instances.

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

For other aggregation operations, you want the 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

If you're running on the 2.1.x development release of Mongo or later, check out the aggregation framework. It's better than the existing group command (but not yet production ready at the time of this answer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM