Is it possible to rename the _id field after aggregation of a mongo group?

I have a query like this (simplified):

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

I am making this request from java and I want to display it in my class, but I do not want the "_id" to be displayed in the "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 a name like "_id", while I want a real identifier to be created.

So how can I rename '_id' after the $ group operation?

+12
source share
4 answers

You can achieve this by adding the $project step at the end of your pipeline, like this:

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

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

+22
source

From mongo v3.4, you can use $addFields in combination with $project to avoid writing all fields to $project , which can be very tedious .

This happens in $project , because if you include only a field, other fields will be automatically excluded.

Example:

 { $addFields: { my_new_id_name: "$_id" } }, { $project: { _id: 0 } } 
+2
source

If you use the find method you cannot do this, but if you use aggregation it is very simple, like this:

 db.collectionName.aggregate([ { $project: { newName: "$existingKeyName" } } ]); 
0
source
  db.report.aggregate( { $group: {_id: '$name'} }, { $project:{ name:"$_id", _id:false} } ) 
0
source

Source: https://habr.com/ru/post/1267008/


All Articles