Is it possible to rename _id field after mongo'

2020-06-07 01:17发布

问题:

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 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?

回答1:

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



回答2:

From mongo v3.4 you could use $addFields in conjunction with $project to avoid to write all the fields in $project that could be very tedious.

This happen in $project because if you include specifically a field, the other fields will be automatically excluded.

Example:

{ 
  $addFields: { my_new_id_name: "$_id" }
},
{
  $project: { _id: 0 }
}


回答3:

 db.report.aggregate(   
{     
$group: {_id: '$name'} 
},
{
$project:{
  name:"$_id",
 _id:false} }
 )


回答4:

if you are using find method you can't do this, but if you using aggregation it is very easy like this:

db.collectionName.aggregate([
    {
        $project: {
            newName: "$existingKeyName"
        }
    }
]);


标签: java mongodb