select only subdocuments or arrays select only subdocuments or arrays mongodb mongodb

select only subdocuments or arrays


Tried this:

db.countries.aggregate(          {        "$project": {            "state": "$states",            "_id": 0        }    },    {        "$unwind": "$state"    },    {        "$group": {            "_id": "$state.name",            "state": {                "$first": "$state"            }        }    },    {        "$match": {            "_id": "orissa"        }    });

And got:

{    "result" : [            {                    "_id" : "orissa",                    "state" : {                            "name" : "orissa",                            "direction" : "east",                            "population" : 41947358,                            "districts" : [                                    {                                            "name" : "puri",                                            "headquarter" : "puri",                                            "population" : 1498604                                    },                                    {                                            "name" : "khordha",                                            "headquarter" : "bhubaneswar",                                            "population" : 1874405                                    }                            ]                    }            }    ],    "ok" : 1


You can't do it right now, but you will be able to with $unwind in the aggregation framework. You can try it now with the experimental 2.1 branch, the stable version will come out in 2.2, probably in a few months.


Any query in mongodb always return root document.

There is only one way for you to load one sub document with parent via $slice if you know ordinal number of state in nested array:

// skip ordinalNumberOfState -1, limit 1db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}}) 

$slice work in default order (as documents was inserted in nested array).Also if you don't need fields from a country you can include only _id and states in result:

db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}, _id: 1}) 

Then result document will looks like this one:

{    "_id":{        "oid":"4f33bf69873dbc73a7d21dc3"    },    "states":[{            "name":"orissa",            "direction":"east",            "population":41947358,            "districts":[{                    "name":"puri",                    "headquarter":"puri",                    "population":1498604                },                {                    "name":"khordha",                    "headquarter":"bhubaneswar",                    "population":1874405                }            ]        }]}