- Installing MongoDB >
- Getting Started with MongoDB Development
Getting Started with MongoDB Development¶
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 a 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.
This tutorial addresses the following aspects of MongoDB use:
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 for context, by default. At any time issue the
following operation at the mongo to report the current
database:
db returns the name of the current database.
From the
mongoshell, display the list of databases with the following operation:Switch to a new database named
mydbwith the following operation:Confirm that your session has the
mydbdatabase as context, using thedboperation, which returns the name of the current database as follows:
At this point, if you issue the show dbs operation again, it will
not include mydb, because MongoDB will not create a database until
you insert data into that database. The
Create a Collection and Insert Documents section describes the process
for inserting data.
Create a Collection and Insert Documents¶
In this section, you insert documents into a new collection
named things within the new database named
mydb.
MongoDB will create collections and databases implicitly upon their first use: you do not need to create the database or collection before inserting data. Furthermore, because MongoDB uses dynamic schemas, you do not need to specify the structure of your documents before inserting them into the collection.
Insert Individual Documents¶
From the
mongoshell, confirm that the current context is themydbdatabase with the following operation:If
mongodoes not returnmydbfor the previous operation, set the context to themydbdatabase with the following operation:Create two documents, named
jandk, with the following sequence of JavaScript operations:Insert the
jandkdocuments into the collectionthingswith the following sequence of operations:When you insert the first document, the
mongodwill create both themydbdatabase and thethingscollection.Confirm that the collection named
thingsexists using 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 isthings. Allmongoddatabases also have asystem.indexescollection.Confirm that the documents exist in the collection
thingsby issuing query on thethingscollection. Using thefind()method in an operation that resembles the following: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 Multiple Documents Using a For Loop¶
From the
mongoshell, add more documents to thethingscollection using the followingforloop:Query the collection by issuing the following command:
The
mongoshell displays the first 20 documents in the collection. Your ObjectId values will be different:
The
find()returns a cursor. To iterate the cursor and return more documents use theitoperation in themongoshell. Themongoshell will exhaust the cursor, and return the following documents:
For more information on inserting new documents, see the insert() documentation.
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. This prevents mongo
from displaying thousands or millions of results at once.
The it operation allows you to iterate over the next 20 results in
the shell. In the previous procedure, the cursor only contained two
more documents, and so only two more documents displayed.
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¶
In the MongoDB JavaScript shell, query the
thingscollection 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 result of this operation follows, although if the ObjectId values will be unique:
Use Array Operations with the Cursor¶
You can manipulate a cursor object as if it were an array. Consider the following procedure:
In the
mongoshell, query thethingscollection 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 Document and Read for a full account of queries in MongoDB.
In this procedure, you query for specific documents in the things
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.
To query for specific documents, do the following:
In the
mongoshell, query for all documents where thenamefield has a value ofmongoby passing the{ name : "mongo" }query document as a parameter to thefind()method:MongoDB returns one document that fits this criteria. The ObjectId value will be different:
Query for all documents where
xhas a value of4by passing the{ x : 4 }query document as a parameter tofind():MongoDB returns the following result set:
ObjectId values are always unique.
Query for all documents where
xhas a value of4, as in the previous query, but only return only the value ofj. MongoDB will also return the_idfield, unless explicitly excluded. To do this, you add the{ j : 1 }document as the projection in the second parameter tofind(). This operation would resemble the following:MongoDB returns the following results:
Return a Single Document from a Collection¶
With the db.collection.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 things collection, issue the
following command:
For more information on querying for documents, see the Read and Read Operations documentation.
Limit the Number of Documents in the Result Set¶
You can constrain the size of the result set to increase performance 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: