2012-07-15 90 views
1

這裏是我的mongdb收藏:如何通過Java驅動程序通過集合函數(如組,數和獨特)來訪問mongodb集合?

{ "_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驅動程序或通過如何Java驅動程序來實現查詢聚合函數收集之上指望。

回答

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 

如果你在蒙戈或更高版本的2.1.x的開發版本上運行,檢查出的聚合框架。它比現有的組命令更好(但在此答案時尚未準備好生產)。

+0

Thanx Alot Mrkut它非常有用! – jad001 2012-07-16 21:23:59

相關問題