Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Find documents matching certain condition for unknown field keys

How can I query a MongoDB collection to find documents with a structure as below? The documents have a field called thing which is a subdocument, and the keys for this field are a form of ID number which will generally not be known by the person writing the query (making dot notation difficult and I assume impossible).

{   
"_id" : 3,
"_id2" : 234,
"thing": 
    {
    "2340945683":
        {"attribute1": "typeA",
         "attribute2": "typeB",
         "attribute3": "typeA"
        },

    "349687346":
        {"attribute1": "typeC",
         "attribute2": "typeB",
         "attribute3": "typeA"
        }           
    },      
    "username": "user1"
}

Say I want to set a filter which will return the document only if some one or more of the fields within thing have the condition "attribute1" : "typeC"?

I need something like

db.collection.find( {thing.ANY_FIELD: $elemMatch:{"attribute1":"typeC"}})
like image 478
John F Avatar asked Oct 14 '25 22:10

John F


1 Answers

You need to start with $objectToArray to read your keys dynamically. Then you can $map properties along with $anyElementTrue to detect if there's any nested field in thing containing {"attribute1":"typeC"}:

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $anyElementTrue: {
                    $map: {
                        input: { $objectToArray: "$thing" },
                        in: { $eq: [ "$$this.v.attribute1", "typeC" ] }                         
                    }
                }
            }
        }
    }
])

Mongo Playground

like image 94
mickl Avatar answered Oct 17 '25 14:10

mickl