I have a collection in MongoDB with many documents that have the same structure.
When I perform a find query with some filters over the collection with this code:
Comment.find(
{
"data.time.s": {
"$gte": "2019-05-13",
"$lte": "2019-05-27"
}
},
{
"data.iaqi.co.v": "$data.iaqi.co.v",
"data.time.s": "$data.time.s",
"_id": 0
}, function (error, datos) {
console.log(datos)
});
I get the following output when I console.log(datos):
[
{
"data" : {
"iaqi" : {
"co" : {
"v" : 3.2
}
},
"time" : {
"s" : "2019-05-14 12:00:00"
}
}
},
{
"data" : {
"iaqi" : {
"co" : {
"v" : 4.7
}
},
"time" : {
"s" : "2019-05-15 00:00:00"
}
}
}
]
The array contains more than 2 objects, but for the purpose of the example I just put 2 of them.
All of the objects in the array have the same structure, just the values of "v" and "s" change on each object.
I just need to extract the values of fields "v" and "s" from each object and save them in a CSV file with this exact format:
Date,Value
2019-05-14 12:00:00,3.2
2019-05-15 00:00:00,4.7
2019-05-17 05:00:00,1
2019-05-19 20:00:00,2.3
2019-05-28 08:00:00,33.4
2019-05-28 10:00:00,18.8
2019-05-28 12:00:00,11.5
2019-05-28 13:00:00,12.4
2019-05-29 06:00:00,6.4
Right now I'm doing some tests trying first to show the mentioned values from the array in console with a for loop (instead of just the console.log(datos) in the first code):
for (var i = 0; i < datos.length; i++) {
console.log(datos[i]['data'['time'['s']]]);
}
But I get the following output in the console:
undefined
undefined
Obviously my syntax is incorrect, but I don't know where is the problem.
What would be the exact syntax to access the array and get the desired values?
Thank you very much to everyone that can throw some light into this.
You're close here. Try this syntax. Instead of nesting those items, separate them like such:
for (var i = 0; i < datos.length; i++) {
console.log(datos[i]['data']['time']['s']);
}
You could also use dot notation to find what you're after:
for (var i = 0; i < datos.length; i++) {
console.log(datos[i].data.time.s);
}
fiddle: https://jsfiddle.net/gn7kyhuz/
var datos = [
{
"data" : {
"iaqi" : {
"co" : {
"v" : 3.2
}
},
"time" : {
"s" : "2019-05-14 12:00:00"
}
}
},
{
"data" : {
"iaqi" : {
"co" : {
"v" : 4.7
}
},
"time" : {
"s" : "2019-05-15 00:00:00"
}
}
}
];
for (var i = 0; i < datos.length; i++) {
console.log(datos[i]['data']['time']['s']);
}