First steps with MongoDB

First steps with MongoDB

We have just installed MongoDB in our machine, and the service is running. We will study how to create databases, collections and how to work with our documents. Also, we will answer those most common questions everybody ask themselves when beginning to work with a new technology.

The first questions we can ask ourselves are:

How do we check the version of MongoDB installed?

We can check it without opening any connection, so:

We will notice that when we open a shell connection MongoDB tells us what version is running

How do we connect to the database from the shell?

By default, mongo looks for a database server running on port 27017 at the localhost server. We can change this settings by using the –host and –port options.

We are connected and we must know how to close this connection

Easy, let’s see:


or using the kill command:

If we do not need to work anymore with MongoDB, how do we stop the database?

By using Ctrl+C or, if it is running as a daemon, killing the process:

We must be carefull when using kill -9 <pid>, this command will cause a sudden drop of the database, and it can result in inconsistency and data loss.

Does MongoDB help us when we are working from the command line?

We have this three levels of help:

  • General:

  • At database level:

  • At collection level:

We are already connected and, to start working, the first task we must do is to create a database. Ok, but where are we? If we have read the output of the connection, we have seen this text “connecting to test”. By default, MongoDB creates a database called “test” and connects us to it if we do not specify another one.

How do we connect to a specific database directly from the shell?

How can we know the current database we are connected to?

By checking the object “db”:

How do we consult the list of databases already created?

We have checked that we are connected to the database we have asked for, however, it has not been created! MongoDB creates both the database and the collection when we insert our first document.

We already know that MongoDB does not have scheme, that is, we do not need to declare the structure and the characteristics of our collections before using them. Therefore, the collection will be created when we insert the first document in it, as we have seen before.

MongoDB creates a set of files per database. These files are stored in the directory we have specified when we have started the mongod service or, by default, at the /var/lib/mongodb/ directory.

How can we change the database we are connected to?

How do we consult the collections of our current database?

How do we delete a collection?

To delete a collection, its data and metadata we will use:

To delete all the documents but not the collection nor the metadata, we will use:

How do we delete a database?

By using the dropDatabase() command we will delete the whole current database, including metadata and also the physic files. The “db” object will still be pointing at the same database.

Why MongoDB creates a _id field per document?

All documents must have a field, called _id, with an unique value. If we do not do it, MongoDB will do it automatically before inserting the document (ObjectId value).

How do we refer to a particular collection for doing operations with it?

We must know the concept of namespace. This refers to the concatenation of the database name, a dot and the collection name. E.g., the namespace of the collection ‘prueba’ in the ‘test’ database will be: ‘test.prueba’.

We have seen that the object ‘db’ points to the current database, hence we can construct that namespace as ‘db.prueba’.

In this way we can do an operation with that collection:

What does the output of the query over a document look like?

How can we do more legible this output?

We have two options for getting the output more legible, pretty() and toArray(). Both return the output like a JSON object. The difference is that toArray() stores data in RAM and, depending on how huge they are, this can be a problem.

This is the aspect of the new output:

How can we limit the number of documents displayed?

For this issue we have the limit option.

We can replace limit(1) with findOne(), which also returns the output like a JSON object.

How do we count the number of documents in a collection?

How do we sort an output?

In the next query we are sorting the output using two fields. First we use the field ‘a’ and, then, the field ‘b’. When we use the value ‘1’ we get the output in ascendent order. For getting it in descendent order we must use the value ‘-1’.


We must remember that the _id field is unique and never changes.

We can insert a single document or an array of documents.


An array of documents:


<projection> is optional and allows us to tell MongoDB the fields to be returned. It is a JSON document in which the value of the field can be 1 or 0 (true or false). If we do not fill this option MongoDB will return all the collection fields, including the _id.


For querying the whole collection

This query returns all documents whose field ‘name’ is equal to ‘Charles’.

This query returns only the field ‘name’ from all our documents.

In this query we return the name and the price from those products which price is greater or equal than 200. We can use all kind of operators, for more information we can go to the official documentation page:

The choices we have for making queries are far more than I have shown here. For those of you interested in a deep studio here is the link to the MongoDB documentation:


justOne is a boolean parameter that allows us to limit the delete to a single document when it is true.


We delete all documents whose field ‘name’ is equal to ‘Charles’.

We delete only the first document from all who satisfy the condition (whose field ‘name’ is equal to ‘Charles’).


The default value of the ‘upsert’ and ‘multi’ options is false. By default, only one document will be updated. For modifying more than one document we must set the the ‘multi’ option to true. The ‘upsert’ option allows us to create a new document when none of the documents in the collection matches our requirements. If upsert is true and there are documents that match the query criteria, update() performs an update.


This sentence will replace the entire document whose _id is equal to 100.

In this document we only modify the value of the ‘y’ field.

This is how we increment the value of the ‘y’ field in 2 units.

With this sentence we add the value ‘yellow’ to the array called ‘arr’.

We set a score of 10 points to all the player whose name is ‘Klaus’.

We add the football to the list of Jacob’s hobbies. If the list does not exist it will be created due to the ‘upsert : true’, but if both the list and the football value already exists, this value will not be duplicated in the list (this is the main characteristic of $addToSet).

We can read the MongoDB documentation in order to get a deeper insight:

How do we know if the statement was made?

Write methods return the status of the operation, including the error code and description if the case. Let us see some examples:


We are now ready to perform the most of the operations that a normal MongoDB user needs.

In the next post we will learn how to use the aggregation framework.

Note: Photo courtesy of and thepathtraveler

Juan Roy

MongoDB Fan & Financial Software Developer

You may also like...

1 Response

  1. June 10, 2015

    […] my post First steps with MongoDB we could see how to make basic queries on the database. Therefore, this is the right moment to take […]

Leave a Reply