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!

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

this is returning me the full db object, no selection is happening
Oh, I see. I misunderstood your question. I have edited my answer.
@syedfaizan Is this what you're looking for?
Thanks bro , you saved my day, forgot to comment yesterday, sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.