Search code examples
javamongodbaggregation-frameworkrename

Is it possible to rename _id field after mongo's group aggregation?


I have a query like this (simplified):

db.collection.aggregate([
  { $match: { main_id: ObjectId("58f0f67f50c6af16709fd2c7") } }, 
  {
    $group: {
      _id: "$name",
      count: { $sum: 1 },
      sum: { $sum: { $add: ["$P31", "$P32"] } }
    }
  }
])

I do this query from Java, and I want to map it on my class, but I don't want _id to be mapped on name field. Because if I do something like this:

@JsonProperty("_id")
private String name;

then when I save this data back to mongo (after some modification) the data is saved with name as _id while I want a real Id to be generated.

So, how can I rename _id after $group operation?


Solution

  • You can achieve this by adding a $project stage at the end of your pipeline like this :

    { $project: {  
          _id: 0,
          name: "$_id",
          count: 1,
          sum: 1
       }
    }
    

    try it online: mongoplayground.net/p/QpVyh-0I-bP