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?
The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. The $project specifications have the following forms: Form. Description.
You cannot update it but you can save a new id and remove the old id.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With