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
}
}
}