Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$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.

like image 377
manoj Avatar asked Jul 12 '18 06:07

manoj


People also ask

What is $Replaceroot in MongoDB?

Definition. Replaces the input document with the specified document. The operation replaces all existing fields in the input document, including the _id field. You can promote an existing embedded document to the top level, or create a new document for promotion (see example).

What is $first in MongoDB?

This means $first returns the first order type for the documents between the beginning of the partition and the current document.

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.

How do I use distinct aggregation in MongoDB?

You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large. The question was to get the city with MOST zip codes for each state, not to get the actual zip codes.


2 Answers

You need to use $replaceRoot to change your root document

db.collection.aggregate([
  {
    "$addFields": {
      "_id.features": "$features"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$_id"
    }
  }
])
like image 163
Ashh Avatar answered Oct 20 '22 05:10

Ashh


db.collection.aggregate([
  {      
      $project: {
                _id: "$_id._id",
                feature_type:"$_id.feature_type",
                feature_name:"$_id.feature_name",
                features:1
                }
  }
])
like image 32
manoj Avatar answered Oct 20 '22 07:10

manoj