MongoDB, select nested arrays fields MongoDB, select nested arrays fields mongodb mongodb

MongoDB, select nested arrays fields


db.collection.find({},{'id':1, 'family.children.toys' :1, '_id':0})

Sample output:

{        "id" : 1000,        "family" : {                "children" : [                        {                                "toys" : [                                        {                                                "name" : "Lego"                                        },                                        {                                                "name" : "Playstation"                                        }                                ]                        },                        {                                "toys" : [                                        {                                                "name" : "Xbox"                                        },                                        {                                                "name" : "Barbie"                                        }                                ]                        }                ]        }}


You can also do this with aggregation. You use the $map operator to return only the toys field.

db.collection.aggregate([{     "$project": {         "family.childrens": {             "$map": {                 "input": "$family.children",                "as": "f",                 "in": { "toys": "$$f.toys" }            }        }     }} ])