In the previous post we saw how to get started with mongodb by installing and starting up the server and the client. In this post let’s create a simple database and add some records.
I was on a TDD assignment last week mentoring a team. Using TDD, we developed a Quiz application that generated a set of questions from a question bank. I maintained the question bank in MongoDB. Let me use that example and show how to create a database called Quiz and add some questions to the database in MongoDB.
- Let’s start the mongodb server and launch the client.
- Create a new database called Quiz using the use command.
use Quiz
It will automatically create a database called Quiz and switch to that database as shown here.
- Add a collection(or table) called Questions using the insert() function(or command) as shown here.
db.Questions.insert(JSON data) is the general format.
db.Questions.insert({question:”1+1=?”,choices:[“1″,”2″,”3″,”4″],answer:”2″})
db.Questions.insert({question:”4+1=?”,choices:[“2″,”3″,”4″,”5″],answer:”5″})
db.Questions.insert({question:”1+2=?”,choices:[“1″,”2″,”3″,”4″],answer:”3″})
db.Questions.insert({question:”8-4=?”,choices:[“1″,”2″,”3″,”4″],answer:”4”})
insert() is a JavaScript function and if you want to find that out you can type
db.Questions.insert without paranthesis and you can see the code for insert function - If you want to see the list of all questions added, use db.Questions.find() function which will show the list of all questions like this.
- You can notice that the questions are added with a primary key value called _id which is a 12-byte value that is a combination of machine id, process id, timestamp and an auto-incremented value.
In the next post, let’s play with some more operations on the Questions data.