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

mongodbmongodb-query

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?

Best Answer

Basically, if you want all attributes of your documents to be passed to the next pipeline you can skip the $project pipeline. but if you want all the attributes except the "_id" value then you can pass

{ $project: { _id: 0 } }

which will return every value except the _id.

And if by any chance you have embedded lists or nests that you want to flatten, you can use the $unwind pipeline

Related Topic