mongodb + aggregation – automatically add fields to $ project

Question:

using ONLY aggregation (i.e. being inside the pipeline ) and $$ROOT create a cursor containing all model fields (automatically) + computed fields. Of course, all fields of the model can be enumerated with pens. But, since one script will work with different collections, the fields need to be inserted automatically.

Option 1 (will not work)

Коллекция.aggregate([{ 
$project:{ 
  fields:"$$ROOT", 
  computedFields: { 
    id:"$_id" 
  } 
} 
}], 
callback) 

Will not work, as it will generate documents of the following type: {fields:{поля объекта}, computedFields:{id:104}}

You need to get it:
{поле1:знач1, поле2:знач2, ... id:104} , where field1, field2, … are fields taken from the collection model automatically.

Option 2 (will not work):

var obj= {поле1:1, поле2:1, ... id:"$_id"} 
Коллекция.aggregate([{ 
  $project:obj 
}], callback) 

Answer:

This feature does not currently exist in MongoDB. You need to either list all the fields in advance, or be content with $$ROOT and change the object structure already in your application code.

Scroll to Top