Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 728
wi3o Avatar asked Aug 15 '17 00:08

wi3o


2 Answers

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

like image 136
Avindu Hewa Avatar answered Nov 15 '22 06:11

Avindu Hewa


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.

like image 31
Aakash Ohri Avatar answered Nov 15 '22 06:11

Aakash Ohri