MongoDB

Insert

Posted on 09th May 2014

The insert() method of a MongoDB collection inserts a document or an array of documents to a collection. The database and collections are created automatically if they do not exist.

Insert a document

To insert a document into a database named myMovieDB,
Connect to mongo shell and select myMovieDB database.

C:\MongoDB\bin> mongo
MongoDB shell version: 3.2.9
connecting to: test
> use myMovieDB
switched to db myMovieDB
> db
myMovieDB
> show collections
>

This will set the current database to myMovieDB. The show collections command confirms that no collections exist in this database.

The following example inserts a document in a collection named movie.

db.movie.insert( 
	{
	title: "Gravity",
 	releaseYear: 2013,
 	language: "English",
 	director: "Alfonso Cuarón",
 	cast: ["Sandra Bullock","George Clooney","Ed Harris","Paul Sharma"]
	}
)

The movie collection is automatically created when the document is inserted.

The next example inserts multiple documents to the movie collection by passing an array of documents to the insert() method.

db.movie.insert(
    [
       {
	title: "The book thief",
 	releaseYear: 2013,
 	language: "English",
 	director: "Brian Percival",
 	cast: ["Sophie Nólisse","Geoffrey Rush","Emily Watson"] 
       },
       {
	title: "Pulp Fiction",
 	releaseYear: 1994,
 	language: "English",
 	director: "Quentin Tarantino"
       },
       {
       	title: "Django Unchained",
        releaseYear: 2013,
        language: "English",
        director: "Quentin Tarantino"
       },
       {
	title: "The Matrix",
 	releaseYear: 1999,
 	language: "English",
 	director: "The Wachowski Brothers"
       }
    ]
)

The array is enclosed in square brackets ([ ]) and each document element in the array is enclosed in curly bracket({}) and seperated by a comma (,).

Confirm myMovieDB database and movie collections are created with the below commands

> show dbs
local   0.078125GB
myMovieDB       0.203125GB
mydb    0.203125GB
>
> show collections
movie
system.indexes
>

The count() method of a collection returns the number of documents in the collection.

> db.movie.count()
5
>

Post a comment

Comments

Nothing yet..be the first to share wisdom.