Find when the keys are unknown in MongoDB?

To find documents when the keys are unknown in MongoDB, use $addFields with $objectToArray to convert documents into key-value arrays, then search through the values dynamically.

Syntax

db.collection.aggregate([
    { "$addFields": {
        "arrayField": { "$objectToArray": "$$ROOT" }
    }},
    { "$match": { "arrayField.v.fieldName": "searchValue" }},
    { "$project": { "arrayField": 0 }}
])

Sample Data

db.demo375.insertMany([
    {
        "details": {
            "Name": "John",
            "Age": 23
        }
    },
    {
        "details": {
            "Name": "David",
            "Age": 21
        }
    },
    {
        "details": {
            "Name": "David",
            "Age": 22
        }
    }
]);

Display all documents to verify the structure ?

db.demo375.find();
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b06"), "details" : { "Name" : "John", "Age" : 23 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }

Example: Find Documents with Unknown Key Structure

Search for documents containing "David" without knowing the exact field path ?

db.demo375.aggregate([
    { "$addFields": {
        "UnknownKeys": { "$objectToArray": "$$ROOT" }
    }},
    { "$match": { "UnknownKeys.v.Name": "David" }},
    { "$project": { "UnknownKeys": 0 }}
]);
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } }
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }

How It Works

  • $objectToArray converts each document into an array of key-value pairs
  • $$ROOT represents the entire document being processed
  • UnknownKeys.v accesses the value portion of each key-value pair
  • $project removes the temporary UnknownKeys field from final output

Conclusion

Use $objectToArray with $$ROOT to search documents when field names are dynamic or unknown. This technique converts documents to searchable key-value arrays, enabling flexible queries across varying document structures.

Updated on: 2026-03-15T02:43:18+05:30

734 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements