12

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 Answer 1

28

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 } } 
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.