JavaScript - - By Michael Wanyoike

Database JSON File

Most relational databases use SQL for data and schema manipulation. However, each DBMS vendor has developed their own SQL dialect. This means exchanging data between different DBMS platforms requires data conversion. This is mostly achieved using third-party tools.


July 27th, 2017: This article series was rewritten with up-to-date information and fresh examples.


With NoSQL databases, most have native support for JSON as an import format. This means you can export data in JSON format from one NoSQL database like Mongo, and import the same data to another NoSQL database like RethinkDB without doing any conversion.

In this example, we are going to look at a JSON file created using a generator that can be imported into a NoSQL database such as Mongo.

products.json:

[{
  "_id": {
    "$oid": "5968dd23fc13ae04d9000001"
  },
  "product_name": "sildenafil citrate",
  "supplier": "Wisozk Inc",
  "quantity": 261,
  "unit_cost": "$10.47"
}, {
  "_id": {
    "$oid": "5968dd23fc13ae04d9000002"
  },
  "product_name": "Mountain Juniperus ashei",
  "supplier": "Keebler-Hilpert",
  "quantity": 292,
  "unit_cost": "$8.74"
}, {
  "_id": {
    "$oid": "5968dd23fc13ae04d9000003"
  },
  "product_name": "Dextromathorphan HBr",
  "supplier": "Schmitt-Weissnat",
  "quantity": 211,
  "unit_cost": "$20.53"
}]

To import this data to a MongoDB, use the following command:

 mongoimport --db api --collection products --drop --jsonArray --file products.json

After importing is complete, login to the database and confirm that the data has indeed been imported:

db.products.find()
 # output
 { "_id" : ObjectId("5968dd23fc13ae04d9000001"), "product_name" : "sildenafil citrate", "supplier" : "Wisozk Inc", "quantity" : 261, "unit_cost" : "$10.47" }
{ "_id" : ObjectId("5968dd23fc13ae04d9000002"), "product_name" : "Mountain Juniperus ashei", "supplier" : "Keebler-Hilpert", "quantity" : 292, "unit_cost" : "$8.74" }
{ "_id" : ObjectId("5968dd23fc13ae04d9000003"), "product_name" : "Dextromathorphan HBr", "supplier" : "Schmitt-Weissnat", "quantity" : 211, "unit_cost" : "$20.53" }

For other NoSQL databases, check their reference manual on how to accomplish the same.

Also: See more JSON examples.

Sponsors