【发布时间】:2017-01-20 06:24:05
【问题描述】:
我正在尝试使用 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"))));
但是,如果我打印出文档,我会得到空文档。
for (Document doc : iterable) {
System.out.println(doc);
}
Document{{_id=null}}
你能解释一下哪一部分是错的吗?
【问题讨论】:
-
在 $group 阶段试试这个: new Document("_id", new Document("date", "$Date").append("time", "$Time") ).append ("count", new Document("$sum", 1)))
-
只投射
ThermalComfort,为什么还要分组?请使用预期输出更新您的问题。 -
@felix,谢谢!有效。但是,我遇到了输出问题。我想以这种方式打印输出。 {date=12/19/16, time=0:00:00, listOfTC = [2,1,3,4,5]},那我应该如何修改我的代码呢?
-
@Veeram 我用预期的输出更新了一个问题。你说得对,我认为我根本不需要项目。
标签: java mongodb aggregation-framework