Агрегирование Mongodb на нескольких полях.Как псевдоним _id поле для сопоставления с соответствующим объектом - PullRequest
0 голосов
/ 01 мая 2019

Ниже приведен запрос mongo db и соответствующий код Java с использованием morphia.Где я хочу, чтобы псевдоним _id поле, когда я агрегирую с несколькими полями.Этот псевдоним поможет мне в создании правильного сопоставления между результатом запроса и объектом Java.

Запрос:

db.ulog.aggregate([
 {
   "$match": {
     "$and": [
       {
         "cdate": {
           "$gte": 1550008600000
         }
       },
       {
         "cdate": {
           "$lt": 1554056999999
         }
       }
     ]
   }
 },
 {
   "$group": {
     "_id": {"channelUserCode":"$pucode","channelActivityCode":"$pacode"},
     "point": {
       "$sum": "$point"
     },
     "count": {
       "$sum": 1
     }
   }
 },
 {
   "$project": {
     "_id": 1,
     "point": 1,
     "count": 1,
   }
 }
])

Результат:

{
    "_id" : {
        "channelUserCode" : NumberLong(709098775838588289),
        "channelActivityCode" : NumberLong(-1525000763901071495)
    },
    "point" : NumberLong(15),
    "count" : 5.0
}

Код Java:

AdvancedDatastore datastore = (AdvancedDatastore) userLogDao.getDatastore();
String collectionName = CalUtils.getUserLogCollectionName(startDate);
Query<UserLog> query = datastore.createQuery(collectionName, UserLog.class);
                query.project(UserLog.ID, true).project(UserLog.CHANNEL_ACTIVITY_CODE,true).
                        project(UserLog.CHANNEL_ACTIVITY_PLATFORM_CODE,true).
                        project(UserLog.POINT,true).project(UserLog.CHANNEL_USER_CODE, true).
                        project(UserLog.USER_ID, true);
                query.field(UserLog.CDATE).greaterThanOrEq(startDate);
                query.field(UserLog.CDATE).lessThan(endDate);

AggregationPipeline pipeline = datastore.createAggregation(collectionName, UserLog.class)
                .match(query)
                .group( id(grouping(UserLog.CHANNEL_USER_CODE), grouping(UserLog.CHANNEL_ACTIVITY_CODE)),
                        grouping("points", sum(UserLog.POINT)),
                        grouping("count", new Accumulator("$sum", 1)))
                .project(Projection.projection("_id"), Projection.projection("points"), Projection.projection("count"));
        //pipeline.aggregate(channelActivityMap);
...