![](/img/trans.png)
[英]How to acces mongodb collection through aggregate function (like group, count and distinct) through java driver?
[英]mongodb java driver aggregate group by
我正在嘗試使用mongodb java驅動程序通過聚合函數編寫組。
這是數據庫的文檔結構。
{ "_id" : ObjectId("58819bd9f16a7802523bc077"), "Date" : "12/19/2016", "Time" : "4:15:00", "Temperature" : 65.5, "User" : "A", "ThermalComfort" : -1, "settingID" : ObjectId("58819bd6f16a7802523bbdc5") }
{ "_id" : ObjectId("58819bd9f16a7802523bc078"), "Date" : "12/19/2016", "Time" : "4:30:00", "Temperature" : 65.25, "User" : "A", "ThermalComfort" : -1, "settingID" : ObjectId("58819bd6f16a7802523bbdc5") }
我想按“日期”和“時間”分組,僅投影ThermalComfort。 我的預期輸出為:{date = 12/19/16,time = 0:00:00,listOfTC = [2,1]}。 listOfTC是由Array中的每個讀數組成的列表:(例如[-1,-1])
這是我寫的代碼。
AggregateIterable<Document> iterable = themalComfortProfileCollection.aggregate(Arrays.asList(
new Document("$group", new Document("_id", "$Date" + "$Time").append("count", new Document("$sum", 1))),
new Document("$project", new Document("comfortIndex", "$ThermalComfort"))));
但是,如果我打印出文檔,我將獲得null文檔。
for (Document doc : iterable) {
System.out.println(doc);
}
Document{{_id=null}}
你能解釋一下哪個部分錯了嗎?
所以,最后,這段代碼返回了我想要的結果。
AggregateIterable<Document> iterable = themalComfortProfileCollection.aggregate(Arrays.asList(
new Document("$group", new Document("_id", new Document("date", "$Date").append("time", "$Time") ).append("ThermalComfortList", new Document("$push", "$ThermalComfort"))),
new Document("$sort", new Document("_id", 1))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.