$replaceRoot in mongodb

I use aggregation framework for group by of multiple fields as

{
_id:{_id:"$_id",feature_type:"$feature_type",feature_name:"$feature_name"},
features: { $push: "$features" }
}

it give result like

{_id:
     {_id:1,feature_type:"Test",feature_name:"Tests"},
  features:["23423","32423","2342342"]
}

but I want result like

{_id:1,feature_type:"Test",feature_name:"Tests",
  features:["23423","32423","2342342"]
}

how can i acheve this using aggregration framework.

2 answers

  • answered 2018-07-12 07:19 Anthony Winzlet

    You need to use $replaceRoot to change your root element

    db.collection.aggregate([
      {
        "$addFields": {
          "_id.features": "$features"
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$_id"
        }
      }
    ])
    

  • answered 2018-07-12 07:35 manoj

    db.collection.aggregate([
      {      
          $project: {
                    _id: "$_id._id",
                    feature_type:"$_id.feature_type",
                    feature_name:"$_id.feature_name",
                    features:1
                    }
      }
    ])