Navigation
This version of the documentation is archived and no longer supported.

Getting Started with MongoDB

This tutorial provides an introduction to basic database operations using the mongo shell. mongo is a part of the standard MongoDB distribution and provides a full JavaScript environment with complete access to the JavaScript language and all standard functions as well as a full database interface for MongoDB. See the mongo JavaScript API documentation and the mongo shell JavaScript Method Reference.

The tutorial assumes that you’re running MongoDB on a Linux or OS X operating system and that you have a running database server; MongoDB does support Windows and provides a Windows distribution with identical operation. For instructions on installing MongoDB and starting the database server, see the appropriate installation document.

Connect to a Database

In this section, you connect to the database server, which runs as mongod, and begin using the mongo shell to select a logical database within the database instance and access the help text in the mongo shell.

Connect to a mongod

From a system prompt, start mongo by issuing the mongo command, as follows:

mongo

By default, mongo looks for a database server listening on port 27017 on the localhost interface. To connect to a server on a different port or interface, use the --port and --host options.

Select a Database

After starting the mongo shell your session will use the test database by default. At any time, issue the following operation at the mongo to report the name of the current database:

db
  1. From the mongo shell, display the list of databases, with the following operation:

    show dbs
    
  2. Switch to a new database named mydb, with the following operation:

    use mydb
    
  3. Confirm that your session has the mydb database as context, by checking the value of the db object, which returns the name of the current database, as follows:

    db
    

    At this point, if you issue the show dbs operation again, it will not include the mydb database. MongoDB will not permanently create a database until you insert data into that database. The Create a Collection and Insert Documents section describes the process for inserting data.

    New in version 2.4: show databases also returns a list of databases.

Display mongo Help

At any point, you can access help for the mongo shell using the following operation:

help

Furthermore, you can append the .help() method to some JavaScript methods, any cursor object, as well as the db and db.collection objects to return additional help information.

Create a Collection and Insert Documents

In this section, you insert documents into a new collection named testData within the new database named mydb.

MongoDB will create a collection implicitly upon its first use. You do not need to create a collection before inserting data. Furthermore, because MongoDB uses dynamic schemas, you also need not specify the structure of your documents before inserting them into the collection.

  1. From the mongo shell, confirm you are in the mydb database by issuing the following:

    db
    
  2. If mongo does not return mydb for the previous operation, set the context to the mydb database, with the following operation:

    use mydb
    
  3. Create two documents named j and k by using the following sequence of JavaScript operations:

    j = { name : "mongo" }
    k = { x : 3 }
    
  4. Insert the j and k documents into the testData collection with the following sequence of operations:

    db.testData.insert( j )
    db.testData.insert( k )
    

    When you insert the first document, the mongod will create both the mydb database and the testData collection.

  5. Confirm that the testData collection exists. Issue the following operation:

    show collections
    

    The mongo shell will return the list of the collections in the current (i.e. mydb) database. At this point, the only collection with user data is testData.

  6. Confirm that the documents exist in the testData collection by issuing a query on the collection using the find() method:

    db.testData.find()
    

    This operation returns the following results. The ObjectId values will be unique:

    { "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
    { "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }
    

    All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.

Insert Documents using a For Loop or a JavaScript Function

To perform the remaining procedures in this tutorial, first add more documents to your database using one or both of the procedures described in Generate Test Data.

Working with the Cursor

When you query a collection, MongoDB returns a “cursor” object that contains the results of the query. The mongo shell then iterates over the cursor to display the results. Rather than returning all results at once, the shell iterates over the cursor 20 times to display the first 20 results and then waits for a request to iterate over the remaining results. In the shell, enter it to iterate over the next set of results.

The procedures in this section show other ways to work with a cursor. For comprehensive documentation on cursors, see Iterate the Returned Cursor.

Iterate over the Cursor with a Loop

Before using this procedure, add documents to a collection using one of the procedures in Generate Test Data. You can name your database and collections anything you choose, but this procedure will assume the database named test and a collection named testData.

  1. In the MongoDB JavaScript shell, query the testData collection and assign the resulting cursor object to the c variable:

    var c = db.testData.find()
    
  2. Print the full result set by using a while loop to iterate over the c variable:

    while ( c.hasNext() ) printjson( c.next() )
    

    The hasNext() function returns true if the cursor has documents. The next() method returns the next document. The printjson() method renders the document in a JSON-like format.

    The operation displays all documents:

    { "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
    { "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
    { "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
    ...
    

Use Array Operations with the Cursor

The following procedure lets you manipulate a cursor object as if it were an array:

  1. In the mongo shell, query the testData collection and assign the resulting cursor object to the c variable:

    var c = db.testData.find()
    
  2. To find the document at the array index 4, use the following operation:

    printjson( c [ 4 ] )
    

    MongoDB returns the following:

    { "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }
    

    When you access documents in a cursor using the array index notation, mongo first calls the cursor.toArray() method and loads into RAM all documents returned by the cursor. The index is then applied to the resulting array. This operation iterates the cursor completely and exhausts the cursor.

    For very large result sets, mongo may run out of available memory.

For more information on the cursor, see Iterate the Returned Cursor.

Query for Specific Documents

MongoDB has a rich query system that allows you to select and filter the documents in a collection along specific fields and values. See Query Documents and Read Operations for a full account of queries in MongoDB.

In this procedure, you query for specific documents in the testData collection by passing a “query document” as a parameter to the find() method. A query document specifies the criteria the query must match to return a document.

In the mongo shell, query for all documents where the x field has a value of 18 by passing the { x : 18 } query document as a parameter to the find() method:

db.testData.find( { x : 18 } )

MongoDB returns one document that fits this criteria:

{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf7"), "x" : 18 }

Return a Single Document from a Collection

With the findOne() method you can return a single document from a MongoDB collection. The findOne() method takes the same parameters as find(), but returns a document rather than a cursor.

To retrieve one document from the testData collection, issue the following command:

db.testData.findOne()

For more information on querying for documents, see the Query Documents and Read Operations documentation.

Limit the Number of Documents in the Result Set

To increase performance, you can constrain the size of the result by limiting the amount of data your application must receive over the network.

To specify the maximum number of documents in the result set, call the limit() method on a cursor, as in the following command:

db.testData.find().limit(3)

MongoDB will return the following result, with different ObjectId values:

{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }

Next Steps with MongoDB

For more information on manipulating the documents in a database as you continue to learn MongoDB, consider the following resources: