Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB object property $exists in nested array

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.

like image 280
Nikola B. Avatar asked Mar 06 '26 08:03

Nikola B.


1 Answers

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 } } 
    }
})
like image 152
NotBad4U Avatar answered Mar 07 '26 22:03

NotBad4U



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!