微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mongodb java驱动程序聚合组

我正在尝试使用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))));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐