MongoDB object property $exists in nested array

2019-01-26 17:00发布

问题:

I have a folowing object structure in my db collection:

{
    "name" : "test",
    "code" : "test",
    "attributes" : [ 
        {
            "name" : "test1",
            "code" : "code1"
        }, 
        {
            "name" : "test2",
            "code" : "code2",
            "value" : true
        }, 
        {
            "name" : "test3",
            "code" : "code3",
            "value" : ""
        }, 
        {
            "name" : "test4",
            "code" : "code4"
            "value" : [ 
                {
                    "code" : "code4.1",
                    "name" : "test4.1"
                }, 
                {
                    "name" : "test4.2"
                }
            ]
        }
    ]
}

So "value" property can be empty string, boolean, array or even not defined at all.

How can I make query to list objects that have non-empty attributes array and don't have "attributes.value" property defined inside at least one object inside array?

p.s. I tried following query:

db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}})

but query result is empty.

回答1:

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

This query work for me:

db.getCollection('testeur').find({ "attributes": {
        $exists: true, 
        $ne: [],
        $elemMatch: { "value": {$exists: false } } 
    }
})