- Install MongoDB >
- Getting Started with MongoDB
Getting Started with MongoDB¶
On this page
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:
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:
From the
mongoshell, display the list of databases, with the following operation:Switch to a new database named
mydb, with the following operation:Confirm that your session has the
mydbdatabase as context, by checking the value of thedbobject, which returns the name of the current database, as follows:At this point, if you issue the
show dbsoperation again, it will not include themydbdatabase. 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 databasesalso returns a list of databases.
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.
From the
mongoshell, confirm you are in themydbdatabase by issuing the following:If
mongodoes not returnmydbfor the previous operation, set the context to themydbdatabase, with the following operation:Create two documents named
jandkby using the following sequence of JavaScript operations:Insert the
jandkdocuments into thetestDatacollection with the following sequence of operations:When you insert the first document, the
mongodwill create both themydbdatabase and thetestDatacollection.Confirm that the
testDatacollection exists. Issue the following operation:The
mongoshell will return the list of the collections in the current (i.e.mydb) database. At this point, the only collection istestData. Allmongoddatabases also have asystem.indexescollection.Confirm that the documents exist in the
testDatacollection by issuing a query on the collection using thefind()method:This operation returns the following results. The ObjectId values will be unique:
All MongoDB documents must have an
_idfield with a unique value. These operations do not explicitly specify a value for the_idfield, somongocreates 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, use 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.
In the MongoDB JavaScript shell, query the
testDatacollection and assign the resulting cursor object to thecvariable:Print the full result set by using a
whileloop to iterate over thecvariable:The
hasNext()function returns true if the cursor has documents. Thenext()method returns the next document. Theprintjson()method renders the document in a JSON-like format.The operation displays all documents:
Use Array Operations with the Cursor¶
The following procedure lets you manipulate a cursor object as if it were an array:
In the
mongoshell, query thetestDatacollection and assign the resulting cursor object to thecvariable:To find the document at the array index
4, use the following operation:MongoDB returns the following:
When you access documents in a cursor using the array index notation,
mongofirst calls thecursor.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,
mongomay 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:
MongoDB returns one document that fits this criteria:
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:
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:
MongoDB will return the following result, with different ObjectId values:
Next Steps with MongoDB¶
For more information on manipulating the documents in a database as you continue to learn MongoDB, consider the following resources: