2017-03-29 95 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