Syed Faizan
Syed Faizan

Reputation: 961

how to query a mongodb using a field which is inside an array of objects

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

Answers (1)

Thomas Bormans
Thomas Bormans

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

Related Questions