1

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!

Syed Faizan
  • 901
  • 3
  • 14
  • 28
  • 1
    possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). Various answers mentioning `.aggregate()` which is suitable for multiple matches. – Blakes Seven Aug 06 '15 at 09:13

1 Answers1

3

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.

Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51