MongoDB queries let you search and analyse your database quickly and ef­fect­ively. The structure of the method is logical, and you can use numerous para­met­ers with it.

How to search col­lec­tions ef­fect­ively

As a document-based NoSQL solution, MongoDB gives users the pos­sib­il­ity to easily store and manage large and diverse amounts of data. The database man­age­ment system is very flexible and can easily be scaled ho­ri­zont­ally.

Unlike with re­la­tion­al databases, data in Mongo DB is stored in BSON documents (binary JSON) and bundled in col­lec­tions. For this approach to really work, it’s important to havestrong query mech­an­isms that can sift through the database and present the in­form­a­tion that users need. With MongoDB queries, the database can even search complexly struc­tured col­lec­tions to deliver the in­form­a­tion you are looking for.

Tip

Is using the shell for MongoDB too confusing? MongoDB Compass is a free graphical user interface that makes nav­ig­at­ing MongoDB easy.

What are MongoDB queries?

MongoDB queries are a user-friendly tool used for searching complex data struc­tures. They follow logical rules and work like the filter options that you find on most websites. This allows you to formulate your search as precisely as possible so you can achieve the best possible results. This is par­tic­u­larly important since MongoDB is able to store many different types of data. Without the necessary filter options, it would be difficult to manage the database. In the following sections, we’ll explain what you need to create MongoDB queries and how to use them.

What are the re­quire­ments for MongoDB queries?

There are only a few re­quire­ments for using MongoDB queries.

  1. You need to have MongoDB installed on your computer. The database works on many operating systems so the in­struc­tions below work whether you are using Linux, OS X or Windows. The steps that come after the in­stall­a­tion are the same on all systems and only affect the database itself. You can find out how the in­stall­a­tion works in our MongoDB tutorial.
  2. You need admin rights to use the search function.
  3. It’s best to create a test en­vir­on­ment so you can try out Mongo DB queries risk-free.

How to structure a test col­lec­tion

First open the shell and log in as ad­min­is­trat­or. Then create a new col­lec­tion that will act as a test en­vir­on­ment for your first MongoDB queries. In addition to searching simple documents, the method can also search arrays, various fields and embedded documents, which is why we’ve decided to create a slightly more complex col­lec­tion. This way you get a better idea of the scope of MongoDB queries.

Our example consists of a list of customers. The format of this list is as follows:

{
    "name" : "Schulz",
    "units" : 642,
    "location" : [ "Germany", "Austria" ],
    "transactions" : {
        "first" : {
            "year" : 2017,
        },
        "last" : {
            "year" : 2023,
        },
        "total" : 14
    }
}
shell

This document contains the following in­form­a­tion:

  • name: The name of the company that purchased the goods.
  • units: The total number of products ordered by the company.
  • location: The location of the company. If there are several branches, these can be saved in the form of an array.
  • trans­ac­tions: This field contains an ad­di­tion­al document inside of it. Documents like this are referred to as ‘embedded documents’ or ‘nested documents’. Each of the trans­ac­tion documents contains in­form­a­tion on how long the company has been a customer (under the ‘first’ item), when the last order was placed (under the ‘last’ item) and the total amount of times the company has ordered products (under the ‘total’ item).

For this example, we’ve added ad­di­tion­al documents to make it easier to include in­form­a­tion at a later point in time. Doing so helps to ensure a good overview of the in­form­a­tion in the database.

Creating a test col­lec­tion for MongoDB queries

Now, we’re going to create a col­lec­tion called ‘Customers’. So it’s easy to keep an overview of the col­lec­tion, we’re only going to include five entries. If you use MongoDB queries for work, you can create more extensive col­lec­tions using the insertMany method.

Here’s what our test col­lec­tion looks like:

db.customers.insertMany ( [
{
    "name" : "Schulz",
    "location" : [ "Germany", "Austria" ],
    "transactions" : {
        "first" : {
            "year" : 2017,
        },
        "last" : {
            "year" : 2023,
        },
        "total" : 14
    }
},
{
    "name" : "ATS",
    "units" : 17,
    "location" : "France",
    "transactions" : {
        "first" : {
            "year" : 2021,
        },
        "last" : {
            "year" : 2022,
        },
        "total" : 2,
    }
},
{
    "name" : "Meyer",
    "units" : 814,
    "location" : [ "Austria", "Germany" ],
    "transactions" : {
        "first" : {
            "year" : 2016,
        },
        "last" : {
            "year" : 2023,
        },
        "total" : 22,
    }
},
{
    "name" : "Pawolski",
    "units" : 313,
    "location" : [ "Germany", "Poland" ],
    "transactions" : {
            "first" : {
            "year" : 2017,
            },
        "last" : {
            "year" : 2020,
        },
        "total" : 9,
    }
},
{
    "name" : "Jorgensen",
    "units" : 7,
    "location" : "Denmark",
    "transactions" : {
        "first" : {
            "year" : 2022,
        },
        "last" : {
            "year" : 2023,
        },
        "total" : 2,
    }
}
] )
shell

When you run this entry with the data we’ve used (or with your own data), you’ll receive a list of object IDs in return. These are unique and ensure that each document can also be found via a cor­res­pond­ing ID. If you want to make sure that all documents have been included in the col­lec­tion, you can use MongoDB find without para­met­ers:

db.customers.find ( )
shell

The output is a list of all object IDs with the complete documents. You can now search them using MongoDB queries.

How to use MongoDB queries with fields and arrays

You can use MongoDB queries to search in­di­vidu­al fields, multiple fields, arrays and embedded documents. We’ll take a look at each in the sections below.

Querying in­di­vidu­al fields with MongoDB queries

The output from MongoDB find shows just how helpful MongoDB queries can be. Our small sample produces an output with long character strings, so you can imagine what it’s like if you’re working with a bigger sample.

In the following example, we’ll also use find, but this time we are going to create a special re­quire­ment that a document has to meet in order to be output. Spe­cific­ally, we’re going to search for all documents that have the name ‘ATS’.

db.customers.find (
    { "name" : "ATS" }
)
shell

Simple MongoDB queries like this one will now search all the documents in the col­lec­tion and match the ones that have the name value ‘ATS’. This only applies to one entry in our col­lec­tion, so the output looks like this:

db.customers.find ( { "name" : "ATS" } )
{
    "_id" : ObjectID ( "673d14684o75iftbb0ct5003" ),
    "name" : "ATS",
    "units" : 17,
    "location" : "France",
    "transactions" : {
        "first" : {
            "year" : 2021,
        },
        "last" : {
            "year" : 2022,
        },
        "total" : 2
    }
shell

Doing it the other way round also works. If you want to display all results except the entry for ‘ATS’, enter the following:

db.customers.find (
    { "name" : { $ne : "ATS" } }
)
shell

If you want to output MongoDB queries with different values, you can do so with an array. We’ll do this using the customers ATS and Jorgensen.

db.customers.find (
    { "name" : [ $in : [ "ATS", "Jorgensen" ] } }
)
shell

Querying multiple fields with MongoDB queries

If you need precise results, it’s important to make your query more specific. You can make your MongoDB queries more precise by using ad­di­tion­al para­met­ers. Below we are going to specify a value from the ‘units’ segment in addition to the company name ‘ATS’. This way, our query searches for a document that contains both values:

db.customers.find (
    { "name" : "ATS", "units" : 17 }
)
shell

We have an exact match. If only one of the two values is a match, no result will be output. Here’s an example of a query with no results:

db.customers.find (
    { "name" : "ATS", "units" : 25 }
)
shell

If you want to take different values into account when using MongoDB queries, but want the query to output a result even when only one of the re­quire­ments is met, enter this:

db.customers.find (
    { $or : [ {"name" : "ATS"}, { "units" : 25 } ] }
)
shell

Querying values in arrays

You can also take values in arrays into account with MongoDB queries. In our col­lec­tion, there are companies that have branches in several countries. If you want to output all companies that have at least one branch in Germany, you can input the following:

db.customers.find (
    { "location" : "Germany" }
)
shell

The output now contains all three customers who have at least one branch in Germany. If you want to expand your input and find companies that have branches in Germany and Austria using the same query, you can use an array:

db.customers.find (
    { "location" : [ "Germany", "Austria" ] }
)
shell

You’ll notice that the input only shows one result, even though two companies the­or­et­ic­ally match the search criteria. The reason for this is that MongoDB queries stick exactly to the input they’re given, which includes the order of the elements. If you want the method to consider values re­gard­less of the order which they appear in, write the query as follows:

db.customers.find (
    { "location" : { $all : [ "Germany", "Austria" ] } }
)
shell

Querying values in embedded documents

In our col­lec­tion, we also have embedded documents, which can also be output using MongoDB queries. To do this, you need to add a period to signal to MongoDB that a field in a nested document should be analysed. For example, if you want a list of all customers who have more than ten trans­ac­tions, enter the following:

db.customers.find (
    { "transactions.total" : { $gt : 10 } }
)
shell

MongoDB accesses the ‘trans­ac­tions’ document and then searches the number of total trans­ac­tions under ‘total’.

How to limit the output of MongoDB queries

The output of MongoDB queries can be quite extensive, which is why it may make sense to limit the output to just a few fields. You can use pro­jec­tions to limit the number of fields shown in the output. These contain the value 1 (fields that should be included in the output) and 0 (fields that shouldn’t be included in the output).

In the following example, we’re going to carry out a two-part query. First, we’re going to initiate a search without para­met­ers using the find method. On its own, it would output all the data in the col­lec­tion. However, we’re going to im­me­di­ately follow it with a pro­jec­tion that only takes the name field into account.

db.customers.find (
    { }
    { "name" : 1 }
)
shell

All the customers will be displayed, but the output will be limited to the names of the companies.

What are cursors and how can I use them in MongoDB queries?

Cursors offer a way to customise how Mongo DB query results are displayed, without changing the actual results of the query. For example, you can limit the number of results that are shown or change their order. If you only want to display two of the results, you can use the limit method. Here’s how:

db.customers.find (
    { }
    { "name" : 1 }
).limit ( 2 )
shell

To sort the output, you can use the following entry. This will display the three customers who have ordered the fewest products:

db.customers.find (
    { }
    { "name" : 1 }
).limit ( 2 ) .sort ( { "units" : 1 } )
shell
Tip

To find a specific document in your database, you can use the MongoDB findONE method. We explain this method in more detail in another article in our Digital Guide.

03dbafd0639d6b099ca9be217b8c0b84

9378b1ddb0084eac26edf8b51e922ecb

b713997fc6bfc4f1f8d7a9ec6d65df69

c9ac60f2f370c12c4028af59a2fea6ae

7dd4860127d59f767354576150e2acbd

03b2f431bad31c7bebd9b9a784e591ba

641becce284983e6cc3064159285947f

26d82365945b0a5f7ffdff0728634590

790acfdc7a291dc8e88a484b74b322e9

Go to Main Menu