The next example will demonstrate how to create a database, and insert a document in a collection using the mongo shell program:
1. In the mongo shell, enter the following command:
>use myfirstdb
2. When the prompt returns, enter the following commands to create documents in a collection named
movies:
>db.movies.insert({name:"Source Code", genre:"sci-fi", year:2011}) >db.movies.insert({name:"The Dark Knight", genre:"action", year:2008}) >db.movies.insert({name:"Megamind", genre:"animation", year:2010}) >db.movies.insert({name:"Paranormal Activity", genre:"horror", year:2009}) >db.movies.insert({name:"Hangover", genre:"comedy", year:2010})
3. The following command returns all documents from the
movies
collection:>db.movies.find()
In step 1, we applied the use myfirstdb
command to switch to a new database namespace. Any collection/document we create now is going to be stored under this database. Next we create a collection named movies and insert some documents in it:
>db.movies.insert({name:"Source Code",genre:"sci-fi",year:2011})
The db
part of the command always refers to the current database, which is "myfirstdb" in this case. The next part is the name of the collection (movies), if it does not already exist in the database, it gets created automatically when you invoke the insert()
method on it. The argument to insert
is a JSON object, a set of key-value pairs. After invoking the first insert
, the database myfirstdb
comes into physical existence. You can look into the data directory at this point, where you will find the files myfirstdb.0, myfirstdb.1
, and so on that are storing the data for this database.
The find()
command, invoked on the collection, returns all the documents in it:
>db.movies.find() { "_id" : ObjectId("4db439153ec7b6fd1c9093ec"), "name" : "Source Code", "genre" : "sci-fi", "year" : 2011 } { "_id" : ObjectId("4db439df3ec7b6fd1c9093ed"), "name" : "The Dark Knight", "genre" : "action", "year" : 2008 } { "_id" : ObjectId("4db439f33ec7b6fd1c9093ee"), "name" : "Megamind", "genre" : "animation", "year" : 2010 } { "_id" : ObjectId("4db439f33ec7b6fd1c9093ef"), "name" : "Paranormal Activity", "genre" : "horror", "year" : 2009 } { "_id" : ObjectId("4db439f43ec7b6fd1c9093f0"), "name" : "Hangover", "genre" : "comedy", "year" : 2010 }
1. What is the default port address of MongoDB?
a. 27107
b. 27017
c. 27170
2. How does a new database get created in MongoDB?
a. By the command
create database <databasename>
b. By the command
use <databasename>
c. By doing
use <databasename>
first and then doingdb.<collectionname>.insert(<jsondocument>)