I have some documents in a Mongodb collection that are of the wrong type, they look like this:
> db.stockData.find({productcode:"EMIM.AS"},{History:1} )
returns
{ "_id" : ObjectId("5cb810770720c53598ea2807")
, "History" : {
"0" : { "year" : 2018, "value" : 22.659 },
"1" : { "year" : 2017, "value" : 25.11 },
"2" : { "year" : 2016, "value" : 20.82 },
"3" : { "year" : 2015, "value" : 18.49 } }
}
The "History" element should be converted to an array, like this:
"History" : [
{ "year" : 2018, "value" : 22.659 }
,"year" : 2017, "value" : 25.11 },
....
] }
Is this doable with JavaScript?
addition:
I was not be able to isolate the History object or loop through it. I used this code
db.stockData.find({productcode:"EMIM.AS"},{History:1} , function( err,doc) { console.log(doc[0].History); });
{ "_id" : ObjectId("5cb810770720c53598ea2807"), "History" : { "0" : { "year" : 2018, "value" : 22.659 }, "1" : { "year" : 2017, "value" : 25.11 }, "2" : { "year" : "2016", "value" : 20.82 }, "3" : { "year" : 2015, "value" : 18.49 } } }
But always got the entire object and not only the History. Apparently used the wrong syntax as it is :
db.stockData.find( {}, {History:1}).forEach(function(doc) {
printjson(doc.History); } );