Q:

Using MongoDB $where to compare elements from Array

Let's assume I have two following MongoDB documents:
{ 
"_id" : ObjectId(a59b0e19aff8a2ed2128bef97"), 
"name" : "John", 
"matches" : [
    {
        "name" : "Bob", 
        "count" : 10
    }, 
    {
        "name" : "John", 
        "count" : 20
    }, 
    {
        "name" : "Alice", 
        "count" : 30
    }
 ]
}

{ 
"_id" : ObjectId(b59b0e19aff8a2ed2128bef97"), 
"name" : "Mike", 
"matches" : [
    {
        "name" : "Bob", 
        "count" : 10
    }, 
    {
        "name" : "John", 
        "count" : 20
    }, 
    {
        "name" : "Alice", 
        "count" : 30
    }
 ]
}

I need to create MongoDB query that will compare "name" with "matches.name".
In my example only first document will be matched because "John" is in the "matches" Array.
Second document will not be matched because Mike is not in the Array.
I tried {$where : "this.matches.name == this.name"} but this doesn't work.
Any ideas?

A:

I believe this may be what you are looking for, an aggregate query looking through matches.$.name to see if any match $name
db.collection.aggregate([{
            "$redact": {
                "$cond": [{
                        "$anyElementTrue": [{
                                "$map": {
                                    "input": "$matches",
                                    "as": "matches",
                                    "in": {
                                        "$eq": ["$$matches.name", "$name"]
                                    }
                                }
                            }
                        ]
                    },
                    "$$KEEP",
                    "$$PRUNE"
                ]
            }
        }
        ])

Which neatly returns
{ 
    "_id" : ObjectId("59c54e6f505e2f07180e60f7"), 
    "name" : "John", 
    "matches" : [
        {
            "name" : "Bob", 
            "count" : 10.0
        }, 
        {
            "name" : "John", 
            "count" : 20.0
        }, 
        {
            "name" : "Alice", 
            "count" : 30.0
        }
    ]
}

