我试图将基于PostgreSQL的应用程序迁移到MongoDB。我使用Morphia连接到MongoDB。
在我的应用程序中,我有这个查询来获取Hibernate的测量列表:
...
jpq = jpq.from(qm)
.where(qm.parameter.eq(parameter));
jpq = jpq.where(qm.dateTime.between(startDate, endDate));
...
case MINUTE:
jpq = jpq.groupBy(qm.dateTime.minute());
case HOUR:
jpq = jpq.groupBy(qm.dateTime.hour());
case DAY:
jpq = jpq.groupBy(qm.dateTime.dayOfMonth());
case MONTH:
jpq = jpq.groupBy(qm.dateTime.month());
case YEAR:
jpq = jpq.groupBy(qm.dateTime.year());
....
我正在尝试在Morphia中创建这样的查询:
db.MongoMeasurement.aggregate(
[
{
$group : {
_id : { month: { $month: "$dateTime" }, day: { $dayOfMonth: "$dateTime" }, year: { $year: "$dateTime" } },
averageValue: { $avg: "$value" },
count: { $sum: 1 }
}
}
]
)
..但我在查找有关如何在Morphia中编写此查询的文档时遇到了问题。
答案 0 :(得分:1)
我没有找到如何在Morphia中编写查询,但我使用Jongo解决了我的问题
....
DB db = mongo.getDB("BD");
Jongo jongo = new Jongo(db);
jongoCo = jongo.getCollection("MongoMeasurement");
....
List<MongoMeasurement> cursor = jongoCo.aggregate("{$group:{"
+ "_id:{ month: { $month: '$dateTime' }, day: { $dayOfMonth: '$dateTime' }, year: { $year: '$dateTime' } },"
+ "value: { $avg: '$value' },"
+ "dateTime:{$min:'$dateTime'},"
+ "count:{$sum:1}"
+ "}}")
.as(MongoMeasurement.class);
答案 1 :(得分:0)
Morphia有一个安静的API来处理聚合。以下是我的项目中的代码段如何按小时分组:
getDs().createAggregation(HuActivity.class)
.group(Arrays.asList(Group.grouping("$hour", "timestamp")), Group.grouping("count", new Accumulator("$sum", 1)))
.aggregate(GroupingModel.class);
集合中的文档如下所示:
{
"_id" : {
"vin" : "WBAWD53538P000001",
"uuid" : "1738d950-871e-4230-8af6-58f19858cc85"
},
"type" : "DISMISSED",
"timestamp" : ISODate("2016-10-30T11:00:00.174Z"),
"payload" : {
"campaignId" : "PERFORMANCE_FIX",
"distinguisher" : 0
}
}