0

I'm trying to get (filter) all the objects from a document array that match the same key.

Document Schema example:

{
    ...
    country: "ES",
    aut_comms: 
    [
        ...
        {name: "Aragon", province: "Huesca"},
        {name: "Aragon", province: "Teruel"},
        {name: "Aragon", province: "Zaragoza"},
        {name: "Madrid", province: "Madrid"}
        ...
    ]
}

If it is possible, im tying to retrieve from the query only the values from the objects that match the same key. Resulting in an array composed like : ["Huesca", "Teruel", "Zaragoza"]

An Array of objects that match the filter will also do the trick:

[
    {name: "Aragon", province: "Huesca"},
    {name: "Aragon", province: "Teruel"},
    {name: "Aragon", province: "Zaragoza"}
]

Thanx

2 Answers 2

2

You will be able to get this array by first unwinding the array and then manipulating it

    db.demo.aggregate([
        {
            $unwind:"$aut_comms"
        },
        {
            $match:{"aut_comms.name":"Aragon"}
        },
        {
            $group:{
                _id:null,
                result: {$push:"$aut_comms.province"}
            }
        }
   ])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank u so much, this accomplishes what i needed :)))
0

Edit

It is indeed possible to do such query and output in your expected format. You can do either $unwind or $match first. Personally, I prefer to do a $match first as it would limit the number of (unnecessary) documents generated by the $unwind operation.

db.getCollection('col').aggregate([
    {$match: {"aut_comms.name": "Aragon"}},
    {$project: {_id: 0, "aut_comms": 1}},
    {$unwind: "$aut_comms"},
    {$match: {"aut_comms.name": "Aragon"}},
    {$project: {"province": "$aut_comms.province"}},
    {$group: {
        _id: null,
        province: {$push: "$province"}
    }}
])

The output will be:

/* 1 */
{
    "_id" : null,
    "province" : [ 
        "Huesca", 
        "Teruel", 
        "Zaragoza"
    ]
}

4 Comments

This is the same as just doing a find operation and then a projection, which will not yield the array that the OP wants
Tried this, but it brings me the whole aut_comms array. Still not filtering by name. Thanx 4 ur help :)
@inikulin I have updated the answer to your expected format.
@Andyk. Thanx mate, both of ur responses are great :)))

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.