How to use MongoDB queries
MongoDB queries let you search and analyse your database quickly and effectively. The structure of the method is logical, and you can use numerous parameters with it.
How to search collections effectively
As a document-based NoSQL solution, MongoDB gives users the possibility to easily store and manage large and diverse amounts of data. The database management system is very flexible and can easily be scaled horizontally.
Unlike with relational databases, data in Mongo DB is stored in BSON documents (binary JSON) and bundled in collections. For this approach to really work, it’s important to havestrong query mechanisms that can sift through the database and present the information that users need. With MongoDB queries, the database can even search complexly structured collections to deliver the information you are looking for.
Is using the shell for MongoDB too confusing? MongoDB Compass is a free graphical user interface that makes navigating MongoDB easy.
What are MongoDB queries?
MongoDB queries are a user-friendly tool used for searching complex data structures. 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 particularly 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 requirements for MongoDB queries?
There are only a few requirements for using MongoDB queries.
- You need to have MongoDB installed on your computer. The database works on many operating systems so the instructions below work whether you are using Linux, OS X or Windows. The steps that come after the installation are the same on all systems and only affect the database itself. You can find out how the installation works in our MongoDB tutorial.
- You need admin rights to use the search function.
- It’s best to create a test environment so you can try out Mongo DB queries risk-free.
How to structure a test collection
First open the shell and log in as administrator. Then create a new collection that will act as a test environment 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 collection. 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
}
}
shellThis document contains the following information:
- 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.
- transactions: This field contains an additional document inside of it. Documents like this are referred to as ‘embedded documents’ or ‘nested documents’. Each of the transaction documents contains information 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 additional documents to make it easier to include information at a later point in time. Doing so helps to ensure a good overview of the information in the database.
Creating a test collection for MongoDB queries
Now, we’re going to create a collection called ‘Customers’. So it’s easy to keep an overview of the collection, we’re only going to include five entries. If you use MongoDB queries for work, you can create more extensive collections using the insertMany
method.
Here’s what our test collection 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,
}
}
] )
shellWhen 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 corresponding ID. If you want to make sure that all documents have been included in the collection, you can use MongoDB find without parameters:
db.customers.find ( )
shellThe 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 individual fields, multiple fields, arrays and embedded documents. We’ll take a look at each in the sections below.
Querying individual 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 requirement that a document has to meet in order to be output. Specifically, we’re going to search for all documents that have the name ‘ATS’.
db.customers.find (
{ "name" : "ATS" }
)
shellSimple MongoDB queries like this one will now search all the documents in the collection and match the ones that have the name value ‘ATS’. This only applies to one entry in our collection, 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
}
shellDoing 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" } }
)
shellIf 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" ] } }
)
shellQuerying 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 additional parameters. 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 }
)
shellWe 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 }
)
shellIf 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 requirements is met, enter this:
db.customers.find (
{ $or : [ {"name" : "ATS"}, { "units" : 25 } ] }
)
shellQuerying values in arrays
You can also take values in arrays into account with MongoDB queries. In our collection, 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" }
)
shellThe 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" ] }
)
shellYou’ll notice that the input only shows one result, even though two companies theoretically 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 regardless of the order which they appear in, write the query as follows:
db.customers.find (
{ "location" : { $all : [ "Germany", "Austria" ] } }
)
shellQuerying values in embedded documents
In our collection, 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 transactions, enter the following:
db.customers.find (
{ "transactions.total" : { $gt : 10 } }
)
shellMongoDB accesses the ‘transactions’ document and then searches the number of total transactions 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 projections 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 parameters using the find
method. On its own, it would output all the data in the collection. However, we’re going to immediately follow it with a projection that only takes the name field into account.
db.customers.find (
{ }
{ "name" : 1 }
)
shellAll 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 )
shellTo 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 } )
shellTo 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.