Aggregation by date in Morphia

限于喜欢 提交于 2020-01-17 02:50:07

问题


I'm trying to migrate a PostgreSQL-based application to MongoDB. I'm using Morphia to connect to MongoDB.

In my app I have this query to get a list of measurements with 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());
....

I am trying to create a query like this in Morphia:

db.MongoMeasurement.aggregate(
           [
             {
              $group : {
                _id : { month: { $month: "$dateTime" }, day: { $dayOfMonth: "$dateTime" }, year: { $year: "$dateTime" } },
                 averageValue: { $avg: "$value" },
                count: { $sum: 1 }
               }
           }
       ]
   )

.. but I'm having trouble finding documentation on how to write this query in Morphia.


回答1:


I dont found how write the query in Morphia, but i solve my problem using 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);



回答2:


Morphia has a quiet good API to deal with aggregation. Here is a code snippet from my project how to group by hours:

 getDs().createAggregation(HuActivity.class)
                .group(Arrays.asList(Group.grouping("$hour", "timestamp")), Group.grouping("count", new Accumulator("$sum", 1)))
                .aggregate(GroupingModel.class);

Where document in collection looks like:

{
        "_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
        }
}


来源:https://stackoverflow.com/questions/25251256/aggregation-by-date-in-morphia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!