query document by field in nested array that may not exist
<p>I have a document representing a rule structured like this </p>

<pre><code>{
    "id" : "34534",
    "name" : "rule1",
    "parameters" : {
        "nodes" : [
            {
                "type" : "x",
                "properties" : {
                    "dataSets" : [
                        {
                            "dataSetKey" : "key"
                        },
                        {
                            "dataSetKey" : "key2"
                        }
                    ],
                    "resource" : {
                        "id" : "4353454"
                    }
                }
            },
            {
                "type" : "y",
                "params" : {}        
            }
        ]
    }
}
</code></pre>

<p>I want to write a query which returns the entire document if it has a node of type x, and within that node it has a dataSet with a dataSetKey of "key".  Unless the node is of type x it will not have a properties field containing the dataSets array.  I've tried this query but it returns 0 documents</p>

<pre><code>db.getCollection('Rules').find({
    "parameters.nodes": {
        $elemMatch: {
            "type": "x",
            "properties.dataSets": {
                $elemMatch: {
                    "dataSetKey": "key"
                }
            }
        }
    }
})
</code></pre>

<p>I've also tried this</p>

<pre><code>db.getCollection('Rules').find({"parameters.nodes.properties.datasets": {$exists: true}},{
    "parameters.nodes": {
        $elemMatch: {
            "type": "x",
            "properties.dataSets": {
                $elemMatch: {
                    "dataSetKey": "key"
                }
            }
        }
    }
})
</code></pre>

<p>but it returns the below error.</p>

<pre><code>"$err" : "Cannot use $elemMatch projection on a nested field (currently unsupported)."
</code></pre>

<p>Any help is greatly appreciated.</p>