How to not list all fields one by one in project when aggregating?

Viewed 12460

I am using Mongo 3.2.14

I have a mongo collection that looks like this:

{
'_id':...
'field1':...
'field2':...
'field3':...
etc...
}

I want to aggregate this way:

db.collection.aggregate{
                        '$match':{},
                        '$project':{
                                    'field1':1,
                                    'field2':1,
                                    'field3':1,
                                    etc...(all fields)
                                    }
                        }

Is there a way to include all fields in the project without listing each field one by one ? (I have around 30 fields, and growing...)

I have found info on this here:

MongoDB $project: Retain previous pipeline fields

Include all existing fields and add new fields to document

how to not write every field one by one in project

However, I'm using mongo 3.2.14 and I don't need to create a new field, so, I think I cannot use $addFields. But, if I could, can someone show me how to use it?

2 Answers

you can use $replaceRoot

db.collection.aggregate{
    "$match": {},
    "$project": {
        "document": "$$ROOT"
    },
    {
        "$replaceRoot": { "newRoot": "$document" }
    }

this way you can get the exact document returned with all the fields in the document...you don't need to add each field one by one in the $project...try using $replaceRoot at the end of the pipeline.

Related