gary69
gary69

Reputation: 4230

query document by field in nested array that may not exist

I have a document representing a rule structured like this

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

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

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

I've also tried this

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

but it returns the below error.

"$err" : "Cannot use $elemMatch projection on a nested field (currently unsupported)."

Any help is greatly appreciated.

Upvotes: 0

Views: 238

Answers (1)

KaSh
KaSh

Reputation: 175

I wonder if it has got to do anything with mongo version? I ran your first query and did get 1 document as a result.

Upvotes: 1

Related Questions