I havee this Json format:
{
"AAPL": {
"cname": "Apple inc",
"symbol": "AAPL",
"logo": "apple.png",
"price": 0
},
"NVDA": {
"cname": "Nvidia Corporation",
"symbol": "NVDA",
"logo": "nvidia.png",
"price": 0
},
"GOOG": {
"cname": "Google inc",
"symbol": "GOOG",
"logo": "google.png",
"price": 0
}
}
I'd like to keep the same format while inserting to the mongoDB. How can i do that using mongoDB native driver for node.js and using the mongo shell.
You have a single JSON object here. When you want each of its keys to be a separate document, you need to transform the object into an array first. While you do that, you also need to move the stock-symbol which is the key of each sub-object into the object itself so it doesn't get lost in the process. You can do this with a Javascript for-in loop:
jsonObject = ... // that JSON code you posted above
var docs = [];
for (var key in jsonObject) {
var doc = jsonObject[key];
doc.symbol = key;
docs.push(doc);
}
You can then pass the whole array to db.collection.insert
to make a batch-insert of all documents in that array.