Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
mykola Avatar asked Apr 21 '17 08:04

mykola


People also ask

What is $project in MongoDB?

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.

Can we rename _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.


1 Answers

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

like image 105
felix Avatar answered Sep 20 '22 12:09

felix