MongoDB Tutorial: How to Use Queries

Mauro ChojrinMon, 11/11/2019 - 08:33

If you’ve been around software development for some time, you’ve probably heard about NoSQL databases.

If you haven’t yet had the chance to work with one, this article is for you.

Here you’ll learn what a NoSQL database is and how to work with one—specifically MongoDB.

Let’s start at the beginning, shall we?

What Is a NoSQL Database, and Why Should You Use One?

A NoSQL (sometimes also referred to as a non-relational) database is a data repository that isn’t based on the relational model.

What this means in practice is that data is usually loosely structured. Contrast that to a relational database, where every record in a particular table has the exact same fields.

Another feature of NoSQL databases is the lack of relational information. In other words, there are no foreign key constraints.

In a way, a NoSQL database is much simpler than an SQL database. And given this simplicity, its performance can be much better than that of its relational counterparts.

That is actually the main reason why you’d want to use one.

NoSQL databases are great for scenarios where the number of read operations heavily outweighs write operations, such as when you’re working with big data or mostly static websites like newspapers.

What Is MongoDB?

MongoDB is an open-source, non-relational database engine.

It’s designed to be used in highly distributed environments. And by that I mean it’s easy to horizontally scale and replicate data.

It can be installed and used on all major current platforms, and it’s simple to use with server-side JavaScript.

For the purposes of this tutorial, I’ll be using a Docker image. You can find detailed installation instructions in MongoDB’s documentation if you want to install it on your server. If you don’t feel like going through the trouble of actually running your own instance of MongoDB, there’s a playground you can use. And if you’re new to Docker, our post on the business case for container technology might come in handy.

For the rest of the article, I’ll assume you have access to a working MongoDB server.

Once you’re connected, you should see a screen like this one:


The first thing we need to do in order to be able to query a database is … create the database, of course. Let’s get to it.

How to Create a New Database

To create a brand new database, you have to use the use command. Like this:

use mydb

This command is twofold:

  • If the database already exists, it simply switches to it for the upcoming queries.
  • If the database doesn’t exist, it first creates the database and then switches to it for further usage.

The Mongo client keeps a pointer to the current database inside the variable db, meaning if you issue a command such as this:


You’ll get this as a response:


In subsequent calls, you’ll be using the db pointer to refer to the currently selected database.

One important little detail: the actual creation of the database (meaning the physical storage of it) will only happen after some data has been input into the database. What does this mean? Well, should you quit Mongo at this time, there won’t be a mydb database there next time you connect to the server.

In MongoDB, objects are called documents and are represented by JSON text.

Object groups are called collections (as opposed to tables, in a relational database), and the objects within those collections are called documents instead of records.

From our point of view, a collection is not much more than a name to reference a document group.

How to Create a New Collection

There are two ways to create a collection in MongoDB: explicit and implicit.

Explicit Collection Creation

In this case, you’ll be using the createCollection() method from the db object, like this:


And then you can start adding documents to it by issuing insert calls.

Implicit Collection Creation

The other way to create a collection is to just call insert on it, like this:

db.mycollection.insert( { 'name': 'John Doe' } )

You should use explicit collection creation if you want to specify options to determine the way the collection will work. (This is a little advanced for the time being, so don’t worry about it too much.)

At this moment, you have some data in your database. So, if you issue this command:

show dbs

You’ll see mydb in the result … which means your data has been stored.

Congratulations! You created your first MongoDB database!

In the following examples, you’ll notice how working with MongoDB is similar to how you’d work with any other JavaScript application you might be familiar with.

How to Issue a Query

Alright! We’re finally getting to the meat of it.

While field definitions have no explicit data type, MongoDB does work with several different data types, which implies different kinds of allowed operations on field values.

Let’s create a few new documents in the database to illustrate (and use in queries later):

db.mycollection.insert( { 'name': 'Jane Doe', 'age': 41 } )

db.mycollection.insert( { 'name': 'Peter Simpson', 'age': 28, 'phones': [ '+1 800 99232', '212 23322' ] } )

Every time you create a new object, an ID will be created for it. Think of it as the primary key.

Now that we have some documents, it makes sense to start looking for information inside our database.

In order to do that, we’ll use the method find:


Just like in any other method call, the find method will accept a JSON object as its parameter. This makes it a powerful query mechanism.

Let’s say you wanted to get people younger than 35. You could issue a query like this one:

db.mycollection.find( { 'age' : { $lte: 35 } } )

Which would result in:

{ "_id" : ObjectId("5d5d7f98fd059b11f5cacab8"), "name" : "Peter Simpson", "age" : 28, "phones" : [ "+1 800 99232", "212 23322" ] }

If you wanted a better formatted result you could use:

db.mycollection.find( { 'age' : { $lte: 35 } } ).pretty()

Which would yield:


   "_id" : ObjectId("5d5d7f98fd059b11f5cacab8"),

   "name" : "Peter Simpson",

   "age" : 28,

   "phones" : [

         "+1 800 99232",

         "212 23322"



And if you wanted to make a more complex query, like people aged 15 to 35:

db.mycollection.find( { '$and': [ { 'age' : { '$lte': 35 } }, { 'age' : { '$gte': 15 } } ] } ).pretty()

If you just wanted to get every document in a collection, you’d issue the following query:


Of course, a collection can contain a lot of documents … and what if you just want a subset of them? Let me introduce you to the limit mechanism.

How to Limit Results on a Query

Let’s assume you have a very populated database.

You most likely won’t be needing every document that matches your query criteria.

In this case, you want to limit the quantity of results you get by using the limit method:


If you don’t want your result to start at the first object, you can use the skip method:


Great, now you can limit the quantity of results you’ll get from any query, which will certainly come in handy when you want to show the results in a paginated fashion.

Another common scenario when it comes to querying for data is the order in which this information will be presented to the user.

It’s time to look at sorting results.

How to Sort Results

In order to get results in a particular order, you have to use the sort method.

This method takes a JSON object as a parameter. The JSON must have a key (which must map to an existing property of the objects to be returned) and an integer expressing the sorting order for that particular field.

For instance, if you wanted to get results ordered by name (in ascending order), you could use this:

db.mycollection.find().sort( { 'name' : 1 } ).pretty()

And, if you wanted to get the same results but in reverse order, you could use this:

db.mycollection.find().sort( { 'name' : -1 } ).pretty()

OK, now that you’ve got an idea about how to do simple queries, let’s get into something a little more complex: regular expressions (yay!).

Before we go any deeper, there’s a question we can’t avoid: why, oh why, would you want to use regular expressions in your queries? Why use regular expressions at all?

The thing is, in spite of their complexity, regular expressions (sometimes shortened as regex) are a powerful tool.

Many times, a lot of similar queries can be written using a single regex, and there are others that simply can’t be expressed any other way.

For instance, if you want to find every document that has a substring within a particular property … good luck doing that without a regex!

So … now that we agree on the usefulness of regex in your queries, let’s see how you can take advantage of them within MongoDB.

How to Use Regular Expressions on Your Queries

There are many ways you can use regular expressions to perform a query.

The one most commonly used is to get a string match on a particular field.

In that case, the syntax you’ll be using is something like this:

db.Collection.find( { field: { $regex: /REG_EX/ } } )

For instance, let’s say you want to get the information on anyone named “Doe.” This is the query you’d be issuing:

db.mycollection.find( { name: { $regex: /Doe/ } } )

Wrapping Up

As you can see, working with MongoDB is similar to working within a JavaScript application.

The query language may not seem as natural as SQL, but it’s equally powerful.

One of the most important differences you’ll see is how to manage object relations. (What a surprise, huh?)

In MongoDB you don’t store the IDs of other documents. Instead you store embedded objects, which eliminates the need for join type operations. (Remember, everything you store in MongoDB is a JSON object, so a field can be another JSON.)

A little heads-up: since there’s no structure in a MongoDB database, it’s fairly easy to make mistakes. There’s no guardian that will prevent you from creating a new collection if you misspell the name of an existing one, for instance. So be extremely careful … and remember, with great power comes great responsibility. 😉

There’s a lot more to know about MongoDB. You can read all about it in the official documentation or sign up for the MongoDB Development Boot Camp