Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JSON with mongo script

I'm trying to write a mongo script to import a jsonArray from a JSON file. My script is in .js format and I execute it with load() command in mongo shell. Is it possible to do it with a mongo script?

I know I can use mongoimport instead. But I want to know a way to do it with a script.

The contents of my current script in which the import part is missing is given below..

var db = connect("localhost:27017/fypgui");
//Import json to "crimes" collection here 
var crimes = db.crimes.find();
while (crimes.hasNext()){
    var item = crimes.next();
    var year =(item.crime_date != null)?(new Date(item.crime_date)).getFullYear():null;
    db.crimes.update( {_id: item._id}, {$set: {crime_year: year}});
}
like image 488
Sampath Liyanage Avatar asked Dec 27 '14 20:12

Sampath Liyanage


People also ask

How do I import a JSON file into MongoDB?

To import JSON file you need to follow the following steps: Step 1: Open a command prompt and give command mongod to connect with MongoDB server and don't close this cmd to stay connected to the server. Step 2: Open another command prompt and run the mongo shell. Using the mongo command.

Can you store JSON in MongoDB?

Does MongoDB use BSON or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.


1 Answers

There is another answer to this question. Even though it's a bit old I am going to respond.

It is possible to do this with the mongo shell.

You can convert your JSON to valid JavaScript by prefixing it with var myData= then use the load() command to load the JavaScript. After the load() you will be able to access your data from within your mongo script via the myData object.

data.js

var myData=
[
        {
                "letter" : "A"
        },
        {
                "letter" : "B"
        },
        {
                "letter" : "C"
        }
]

read.js

#!/usr/bin/mongo --quiet

// read data

load('data.js');

// display letters

for (i in myData) {
  var doc  = myData[i];
  print(doc.letter);
}

For writing JSON is easiest to just load your result into a single object. Initialize the object at the beginning with var result={} and then use printjson() at the end to output. Use standard redirection to output the data to a file.

write.js

#!/usr/bin/mongo --quiet

var result=[];

// read data from collection etc...
for (var i=65; i<91; i++) {
  result.push({letter: String.fromCharCode(i)});
}

// output
print("var myData=");
printjson(result);

The shebang lines (#!) will work on a Unix type operating system (Linux or MacOs) they should also work on Windows with Cygwin.

like image 111
David H. Bennett Avatar answered Oct 23 '22 03:10

David H. Bennett