import json into mongodb

60 views
Skip to first unread message

ruffster123

unread,
Jul 4, 2016, 2:11:22 PM7/4/16
to mongodb-user
Hi, I'm new to mongodb and I have a simple question.  I need to know how to import json into mongodb.  Specifically I want to get rid of the new line breaks between objects in a json formatted file so that I won't have to use the --jsonArray.  Anyone know how I can get rid of the new line character at the end of each object using javascript?

Amar

unread,
Jul 6, 2016, 11:04:10 PM7/6/16
to mongodb-user

Hello,

I need to know how to import json into mongodb

Importing json data to MongoDB can be done using mongoimport.

Specifically I want to get rid of the new line breaks between objects in a json formatted file so that I won’t have to use the —jsonArray

Newlines will be ignored by mongoimport. Here is an example of a file to be imported:

{"_id":"1","a":1.0,"b":2.0,"c":3.0}
{"_id":"2","a":4.0,"b":5.0,"c":6.0}
{"_id":"3","a":7.0,"b":8.0,"c":9.0}

New lines like the following would be ignored:

{"_id":"1","a":1.0,
"b":2.0,
"c":3.0}

{"_id":"2","a":4.0,"b":5.0,"c":6.0}

{"_id":"3","a":7.0,"b":8.0,"c":9.0}

importing this data with mongoimport:

$ mongoimport -d test -c testimport test.json
2016-07-06T15:47:33.465+1000    connected to: localhost
2016-07-06T15:47:33.514+1000    imported 3 documents
$

When imported the collection testimport will be populated properly:

> db.testimport.find()
{ "_id" : "1", "a" : 1, "b" : 2, "c" : 3 }
{ "_id" : "2", "a" : 4, "b" : 5, "c" : 6 }
{ "_id" : "3", "a" : 7, "b" : 8, "c" : 9 }
>

The --jsonArray is only needed if you are importing a json array, which would look like:

[
    {"_id":"1","a":1.0,"b":2.0,"c":3.0},
    {"_id":"2","a":4.0,"b":5.0,"c":6.0},
    {"_id":"3","a":7.0,"b":8.0,"c":9.0}
]

Which would be imported with —jsonArray option:

$ mongoimport --db testdb --collection testcollection --jsonArray --file testArray.json
2016-07-07T09:58:36.154+1000    connected to: localhost
2016-07-07T09:58:36.202+1000    imported 3 documents
$

If you still have issues with importing, could you please provide:

  • Example of the json data you are trying to import
  • How this data was created
  • Any specific error messages that you are getting

Regards,

Amar

Reply all
Reply to author
Forward
0 new messages