Reputation: 961
I have a db object like this:
{
"_id": ObjectID("55c247f94b0c25e5d90d0f39"),
"districts": [
{
"district": "Bangalore Urban",
"stateID": 2,
"districtID": 1
},
{
"district": "Tumkur",
"stateID": 2,
"districtID": 2
}
]
}
and i have stateID with me, what mongoose query should i write to get all objects from the array districts
having the stateID 2
Please help!
Upvotes: 1
Views: 110
Reputation: 5362
You will need an aggregate
query. Your Mongo query will look like this:
db.collection.aggregate([{
$unwind: 'districts'
}, {
$match: {
'stateID': 2
}
}, {
$group: {
_id: null,
'districts': {
$push: '$districts'
}
}
}]);
$unwind
creates a record from each item inside an array.
$match
is your query for finding items of your stateID
$group
groups all your results in a custom key districts.
Upvotes: 3