Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB, select nested arrays fields

I've got a collection were documents have nested arrays, and I would like to select only the lower arrays, is it possible?

I have tried this but it doesn't work:

db.collection.find({},{'family.children.$.toys' :1})

document example

   {
    "id":1000,
    "name": "Bob",
    "surname":"The Builder",
    "family":{
        "size":2,
        "status": "happy",
        "children":[{
            "name":"Jim",
            "school": "St. Mary",
            "toys":[{
                "name":"Lego"
            },
            {
                "name":"Playstation"
            }]
        },
        {
            "name":"Kate",
            "school": "St. Mary",
            "toys":[{
                "name":"Xbox"
            },
            {
                "name":"Barbie"
            }]
        }
        ]
    }
}

Expected result (extract only toys list):

{
_id:1000,
family:{
    childrens:[{
        toys:[{
            name:Lego
        },
        {
            name:Playstation
        }]
    },
    {
        toys:[{
            name:Xbox,
        },
        {
            name:Barbie
        }]
    }
    ]
}}
like image 739
MQ87 Avatar asked Sep 22 '15 15:09

MQ87


2 Answers

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"
                                        }
                                ]
                        }
                ]
        }
}
like image 90
Cetin Basoz Avatar answered Sep 29 '22 00:09

Cetin Basoz


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" }
            }
        }
     }}
 ])
like image 29
styvane Avatar answered Sep 29 '22 00:09

styvane