How can I import the JSON file consists of more than 200 documents in the mongodb

advertisements

I have created a demodb.json file (having 10 documents) and kept it in my system's D:\ drive

contents of demodb.json are:

[{"ID": 1,"Name": "Kabul","CountryCode": "AFG","District": "Kabol","Population": 1780000}, {"ID": 2,"Name": "Qandahar","CountryCode": "AFG","District": "Qandahar","Population": 237500}, {"ID": 3,"Name": "Herat","CountryCode": "AFG","District": "Herat","Population": 186800}, {"ID": 4,"Name": "Mazar-e-Sharif","CountryCode": "AFG","District": "Balkh","Population": 127800}, {"ID": 5,"Name": "Amsterdam","CountryCode": "NLD","District": "Noord-Holland","Population": 731200}, {"ID": 6,"Name": "Rotterdam","CountryCode": "NLD","District": "Zuid-Holland","Population": 593321}, {"ID": 7,"Name": "Haag","CountryCode": "NLD","District": "Zuid-Holland","Population": 440900}, {"ID": 8,"Name": "Utrecht","CountryCode": "NLD","District": "Utrecht","Population": 234323}, {"ID": 9,"Name": "Eindhoven","CountryCode": "NLD","District": "Noord-Brabant","Population": 201843}, {"ID": 10,"Name": "Tilburg","CountryCode": "NLD","District": "Noord-Brabant","Population": 193238}]

My Mongodb location is: D:\SanMongoDB

All my database and collections stored in D:\SanMongoDB\MongoData

contents of demodb-->city collection is as below

{  "_id":ObjectId("51892b40842d69f5fa21962f"),
   "Name": "India",
   "CountryCode": "IND",
   "District": "ODISHA",
   "Population": 2050000
}

I started Mongod server then open mongo client In mongo client I did the following:

use demodb mongoimport -d demodb -c city --type json --file demodb.json --jsonarray

But i found error as below

Thu May 09 08:21:57.861 Javascript execution failed:SyntaxError:Unexpected identifier

Kindly suggest what I need to do so I can easily import the Json file into the exisiting database of Mongodb.


Assuming your stuff is in file.json, try sed -e 's/ID/_id/g;s/\([^:]*\):\([^,}]*\)/"\1":"\2"/g' file.json | mongoimport --collection collection-name. You can get sed for Windows from GNUWin32. Let me know if you have further problems.

Here, s/ID/_id/g substitutes every occurrences of ID with _id in the file file.json and the second quotes every word to make your file valid JSON. After the two transformations, mongoimport works fine.