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

后端 未结 4 1096
青春惊慌失措
青春惊慌失措 2020-12-30 19:34

I have a query like this (simplified):

db.report.aggregate([{
        $match: {
            main_id: ObjectId(\"58f0f67f50c6af16709fd2c7\")
        }
    },          


        
相关标签:
4条回答
  • 2020-12-30 20:02

    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 }
    }
    
    0 讨论(0)
  • 2020-12-30 20:02

    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"
            }
        }
    ]);
    
    0 讨论(0)
  • 2020-12-30 20:06

    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

    0 讨论(0)
  • 2020-12-30 20:06
     db.report.aggregate(   
    {     
    $group: {_id: '$name'} 
    },
    {
    $project:{
      name:"$_id",
     _id:false} }
     )
    
    0 讨论(0)
提交回复
热议问题