Commonly used Queries in MongoDB

David EketeDavid Ekete
5 min read

In this article, we'll look at some of the most commonly used query methods in MongoDB. We'll be using the MongoDB compass and the MongoDB shell to navigate and manipulate a simple database.

Prerequisites

To comprehend this tutorial, it is expected that you have the requirements listed in the subsections below.

Personal Prerequisites

You should have a basic understanding of;

  • MongoDB
  • MongoDB queries
  • MongoDB shell

Technical Prerequisites

You should have the following installed if you satisfy the above requirements;

  • MongoDB
  • MongoDB compass
  • MongoSH

Setting up Development Environment

Follow the instructions below to get started:

  1. Open MongoDB compass on your machine.
  2. Create a new database with the name ’commerce’.
  3. Create a collection with the name ‘products’.

Note: you may choose your own naming convention for the database and collection.

You'll be using fake JSON data from the link below for this tutorial. Copy the JSON data and add it to your collection.

FakeStoreApi

To add the JSON data to your collection click the Add Option button on MongoDB compass,

Screenshot (160).png

select the Insert Document,

Screenshot (161).png

paste the fake JSON data, then hit the Insert button.

When the insertion is done your development environment should look like this.

Screenshot (147).png

I'll use MongoDB Compass' built-in terminal because it supports IntelliSense and has an autocompletion feature. I highly recommend using MongoDB compass' inbuilt terminal. However, you can use any terminal you want as long as you enable MongoSH.

Before we start, Make sure you're in the correct database. By default, you should be in the test database. Run the code below to change to the commerce database.

use commerce

Note: MongoDB is case sensitive I.e commerce ≠ Commerce

switch-mongodb-database.png

Note: db denotes the current database we’re in, in this case, ‘commerce’.

Since we’re going to be working with one collection, let’s store it in a variable as an alternative to typing out db.products.{query} every single time we want to run a query. To create a variable run let products=db.products, then run products.find() to confirm that you did it correctly. It should return a list of all the elements in the collection and display the first 20.

mongodb-find.png

Basic Queries

Here’s a review of some basic queries;

Note: Most methods don’t return documents on their own, they are commonly used with the find method

MethodParameter(s)Output
.find(){filter condition}:optionalReturns all elements in the database and displays the first 20, displays more when you enter it in your terminal. This iterates the next 20.
.find().sort(){ valid data field: 1 or -1} 1 for ascending order -1 for descending order example:{description: -1}Returns sorted list (descending order) of the first 20 elements, returns more when you enter it which means iterate.
.find().limit()A valid positive number. Example limit(5)Returns first 5 elements.

Complex Queries and Applications

A special query operator, denoted by the dollar sign $, is required to run a complex query.

Below is a list of commonly used complex queries.

Greater than & Less than

Denoted by $gt and $lt respectively. As their names imply the queries return all the values greater than and less than the specified value respectively, without including the specified value. As a test case let's return a list of prices than are greater than and less than 200 respectively. Run the code below for the greater than query;

products.find({price: {$gt: 200}})

mongodb-greater-than.png

As depicted in the image above, the query returned all products with prices greater than 200.

Run the code below for the less than query;

products.find({price: {$lt: 200}})

mongodb-less-than.png

As depicted in the image above, the query returned all products with prices less than 200.

In & not In

Depicted by $in and $nin respectively. The queries return the elements where the value of a field is in the specified array of values and where the value of a field is not in the specified range of values respectively. Run the code below for the $in query.

products.find({price: {$in: [64,109,56.99]}})

The code block above reads “find all products with a price of 64,109 or 56.99”

Screenshot (153).png

The query returned all products whose prices were specified in the array, as shown in the image above.

Run the code below for the $nin query.

products.find({price: {$nin: [64,109,56.99]}})

The code block above reads “find all products that have prices that are neither 64,109 nor 56.99”

Screenshot (154).png

The query returned all products whose prices were not specified in the array, as shown in the image above.

or & and

Depicted by $or and $and respectively. The $or operator returns documents that match either of the queries passed in the array of queries. The $and operator returns documents that match all of the queries passed in the array of queries. You may decide to use a comma, instead of the $and operator when specifying a separated list of expressions. Because MongoDB infers an implicit $and operation when a comma, is used to separate a list of expressions. Run the code snippet below for the $or operator.

products.find({$or: [{price: {$lt: 50}},{category: "electronics"}]})

mongodb-or-operator.png

The query returned all products that had a price less than 50 and also returned all products in the electronics category.

Run the code snippet below for the $and operator.

products.find({$and: [{price: {$lt: 3000}},{price: {$gt: 700}},{category: "electronics"}]})

OR

products.find({price: {$lt: 3000},price: {$gt: 700},category: "electronics"})

The code snippets above will return the same document(s), in the first snippet the $and was explicitly declared, and in the second it was implicitly declared by MongoDB.

Screenshot (156).png

Both queries yielded the same result, as shown in the image above.

Conclusion

There are still a lot of queries used in MongoDB like;

This article only covers some of the most commonly used queries. I hope that goes a long way to help in your coding journey. Happy coding!.

30
Subscribe to my newsletter

Read articles from David Ekete directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

David Ekete
David Ekete

Backend Engineer and JavaScript / TypeScript Developer with a growing interest in exploring and contributing to emerging technology