Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda