2017-03-29 51 views
-2

如何在java中实现这个聚合查询我不知道该怎么做?mongodb聚合函数在java驱动中的实现

db.History.aggregate([ 
    { "$match" : {"thId":"001"}}, 
    { "$group" : { 
       "_id" : {"Id":"$Id","controller" : "$controller","mod" : "$mod","variable" : "$variable"} 
       ,"variable" : {"$first": "$$ROOT"} 
       ,"data" : {"$push":{"value":"$value","updatedDateTime":"$updatedTime"}} 
      } 
    } 
    ]) 
+0

你能证明你已经尝试过什么, – radhakrishnan

回答

0

参考蒙戈Java驱动程序Documentation

 MongoClient mongoClient = new MongoClient("localhost",27017); 
     MongoDatabase database = mongoClient.getDatabase("Test"); 
     MongoCollection<Document> collection = database.getCollection("History"); 
     Document doc = new Document(); 
     doc.append("$match",new Document("thId","001")); 
     Document group = new Document(); 

     group.append("$group", new Document("_id",new Document().append("Id", "$Id").append("controller", "$controller").append("mod" , "$mod").append("variable" , "$variable")) 
     .append("variable" , new Document("$first", "$$ROOT")) 
     .append("data",new Document().append("$push", new Document().append("value", "$value").append("updatedDateTime","$updatedTime")))); 
     ArrayList<Document> docList = new ArrayList<Document>(); 
     docList.add(doc); 
     docList.add(group); 

     List<Document> results =collection.aggregate(docList).into(new ArrayList<Document>()); 
     for(Document res: results){ 
      System.out.println(res.toJson()); 
     } 
+0

太感谢你了.... – venkat