Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
How to iterate through every single key in a document MongoDB

I have a very large document in mongodb but as it is schema less, how do you iterate through it - to know the keys and "do something" to the values based off of conditions.

example data - but unlimited nesting and types

{ 
    "_id": 123, 
    "max" : { "max": "2022-01-22" },
    "string" : "string",
    "object" : {
        "a": "a",
        "nestedObject": {
            "more": 123
        }
    },
    "array" : [1,3,4,5,["another", "array", {"name": "test"}]]
} 


I have gotten to the point where you have to use JavaScript


for (var key in a) {
    if (a.hasOwnProperty(key)) {
        console.log(key + " -> " + a[key]);
    }
}

and get these results:

_id -> 123
max -> [object Object]
string -> string
object -> [object Object]
array -> 1,3,4,5

but what I would like to know if there is an automated way to get into nested values and print them out.

Example of output:

_id -> 123
max -> 
     --> max-> 2022-01-22
string -> string
object -> 
     --> a -> a
     --> nestedObject 
          --> more -> 123
array -> 1,3,4,5
     --> "another", "array"
         --> object
             --> name -> "test

I am thinking you'd have to add type checks to see if there is an object or if type is an array to continue the check, but how do you write a script to know when to stop when it reaches the end of its nested object?


for (var key in a) {
    if (a.hasOwnProperty(key)) {
        console.log(key + " -> " + a[key]);
        if ( typeof(key) == "object") {
        //do something
        } else if ( Array.isArray(a.key) == true) {
        //do something
        }
    }
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!