Januka samaranyake
Januka samaranyake

Reputation: 2597

Aggregation with nested Json

Earlier my mongodb document is look like follows

{
   "_id" : ObjectId("5880f010706358aab7a290af"),
   "user_id" : "2",
   "timezone" : "5.5" 
}

And my following code works fine

 private void getData(String id, String name) throws Exception {
     Aggregation aggregation = newAggregation(
     match(Criteria.where("user_id").is(id)),
     group("timezone").count().as("total"));

     AggregationResults<MongoResultCount> groupResults = mongoTemplate.aggregate(aggregation, "user_log", MongoResultCount.class);
     List<MongoResultCount> resultList = groupResults.getMappedResults();
  }

private class MongoResultCount {
     private String _id;
     private long total;
    }

due to requirements my mongo document now look like follows

{
    "_id" : ObjectId("5880f010706358aab7a290af"),
    "user_id" : "2",
    "meta_data" : {
        "user_data" : {
            "timezone" : "5.5",
        }
    }
}

How do I achieve same that achieved earlier. I searched a solution but not found yet.

Upvotes: 2

Views: 643

Answers (1)

s7vr
s7vr

Reputation: 75934

Use dot notation to access the fields.

Something like

Aggregation aggregation = newAggregation(
     match(Criteria.where("user_id").is(id)),
     group("meta_data.user_data.timezone").count().as("total"));

Upvotes: 1

Related Questions