Importing .JSON file into your remote mongoDB database with MongoHQ


MongoHQ is the first DBaaS (Database as a Service) of its kind. It provides free hosting space to your non-commercial mongo powered apps. First register at mongoHQ and create your database. Then they will provide the details for the terminal operations as follows.
1
mongo widmore.mongohq.com:10010/course -u -p
Here course is my db name. Now Lets import the following grades.json file into the course db.
1

{
"student" : "Joe", "assignment" : "hw1", "grade" : 90 }
{
"student" : "Joe", "assignment" : "hw2", "grade" : 80 }
{
"student" : "Joe", "assignment" : "hw3", "grade" : 85 }
{
"student" : "Joe", "assignment" : "exam", "grade" : 100 }
{
"student" : "Steve", "assignment" : "hw1", "grade" : 80 }
{
"student" : "Steve", "assignment" : "hw2", "grade" : 90 }
{
"student" : "Steve", "assignment" : "hw3", "grade" : 100 }
{
"student" : "Steve", "assignment" : "exam", "grade" : 100 }
{
"student" : "Amanda", "assignment" : "hw1", "grade" : 100 }
{
"student" : "Amanda", "assignment" : "hw2", "grade" : 90 }
{
"student" : "Amanda", "assignment" : "hw3", "grade" : 80 }
{
"student" : "Amanda", "assignment" : "exam", "grade" : 100 }
{
"student" : "Susan", "assignment" : "hw1", "grade" : 100 }
{
"student" : "Susan", "assignment" : "hw2", "grade" : 90 }
{
"student" : "Susan", "assignment" : "hw3", "grade" : 85 }
{
"student" : "Susan", "assignment" : "exam", "grade" : 80 }
Go to the terminal and execute the following command.
1
mongoimport -h widmore.mongohq.com --port 10010 -d course -c grades -u supun -p ******** --type json --file /Desktop/grades.json
Here are the list of options which have used above.
Option Description
-h This parameter specifies the host (or server) name.
--port This parameter specifies the port on the host that the MongoDB database is listening on. It is --portinstead of -p to prevent confusion with the password parameter.
-d The name of your database.
-c The name of the collection to import the CSV file into.
-u Since MongoHQ requires authentication, the database username that you specified.
-p The database password that you specified.
--type The format of the file to be imported … generally CSV or JSON.
--file The physical location of the file … generally on your computer.
--headerline This simply tells MongoDB to disregard the first line of the CSV file.
Now lets query this using our nodejs application.
app.js
1
var MongoClient = require('mongodb').MongoClient;MongoClient.connect('mongodb://supun:********@widmore.mongohq.com:10010/course', function(err, db) {
if(err) throw err;//var query = { 'grade' : 100 };
db.collection(
'grades').find().sort([["grade",-1]]).toArray(function(err, docs) {
if(err) throw err;console.dir(docs);db.close();
});
});
Now execute npm install mongodb
then node app.js
Here is the result.
1
{ _id: ObjectId("521c44526b39dd11b60564d7"), student: "Joe", assignment: 

Comments