THE Queries MongoDB's methods (or « queries ») allow you to search and analyze your database quickly and efficiently. The method structure is very logical and allows for many parameters to be used to specify queries.
Search collections efficiently
As a document-based NoSQL solution, MongoDB offers the ability to easily store and manage large and varied amounts of data. The database management system is very flexible and easily scalable horizontally.
Unlike relational databases, data here is stored in BSON (Binary JSON) documents and grouped into collections or sets. For this approach to really work, it is necessary to powerful query mechanisms that filter the database and present only the information that is really needed. These MongoDB queries scan even the largest collections and provide the information you are looking for.
Advice
Does using MongoDB via the shell seem too complicated? With MongoDB Compass, there is a free graphical user interface that makes it easy to use.
MongoDB Queries: Definition
MongoDB queries are a handy tool for search for complex data structures. They follow logical rules and work like the filter options known on many websites. This gives you the opportunity to formulate your search as precisely as possible and to get the best possible results. This is especially important since MongoDB offers the option to store many different types of data. Without the necessary filtering possibilities, it would be difficult to manage the database satisfactorily. Learn how to easily create Queries on MongoDB and how to use them to your advantage in our step-by-step guide.
What are the requirements on MongoDB Queries?
In order to use MongoDB Queries, there are a few prerequisites.
- First, you need to install MongoDB on your computer. The database works on many operating systems, so whether you're using Linux, macOS, or Windows doesn't make much difference for this guide. The steps beyond installation are the same on all systems and only concern the database itself. To learn how the installation works, check out our MongoDB tutorial.
- To be able to create queries, you must have the administration rights.
- It is best to create a test environment so that you can try the method without risk.
Creating a test collection
Open the shell and log in with your administrative rights. Then, create a new collection that will serve as a test environment for your first MongoDB queries. Since the method can handle simple documents but also tables, different fields or embedded documentswe'll create a slightly more complex collection to demonstrate the scope of MongoDB Queries.
In our example, this is a list of customers. The format of this list is as follows:
{
"name" : "Desbois",
"units" : 642,
"location" : ["France", "Belgium" ],
"transactions" : {
"first" : {
"year" : 2017,
},
"last" : {
"year" : 2023,
},
"total" : 14
}
}
shell
This document contains the following information:
- name : the name of the customer company that purchased the goods.
- units : the total number of products the company has ordered.
- rental : the headquarters of the other company. If there are multiple branches, they can be recorded in table form.
- transactions : this field contains another document that is included (in English, we speak of embedded documents Or nested documents). Each of these transactional documents contains information on the date the company became a customer (under « first »), the date of the last order (under « last ») and finally the total number of orders (under « total »).
In this case, the additional documents have been inserted so that further information can be added later. This helps to preserve the overview.
Creating the test collection for MongoDB Queries
We will now create a collection named « customers » which, for our example, will only contain five entries for a better overview. If you later use MongoDB Queries professionally, you can create much larger collections. To do this, you use the method insertMany
. For our example, it looks like this:
db.clients.insertMany ( [
{
"name" : "Desbois",
"units" : 642,
"location" : ["France", "Belgium" ],
"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" : ["Luxembourg", "Germany" ],
"transactions" : {
"first" : {
"year" : 2016,
},
"last" : {
"year" : 2023,
},
"total" : 22,
}
},
{
"name" : "Romain",
"units" : 313,
"location" : ["France", "Spain" ],
"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
If you enter this as is or with your own data, you get back the list of assigned object IDs. These are unique: they allow each document to be found by its ID. If you want to make sure that all documents have been included in the collection, you can use MongoDB find and thus do without additional parameters:
The output is a list of all object IDs with the full documents, which you can now browse with MongoDB Queries.
Querying Individual Fields with MongoDB Queries
This output already allows you to see the added value of MongoDB queries. In our example, the output will produce long strings that will make searching without tools very difficult. So we will use the method find
by specifying our search. To do this, we define a special requirement that a document must meet to be edited. So, we will search for all documents whose name matches the value « ATS ».
db.clients.find (
{ "name" : "ATS" }
)
shell
Simple MongoDB queries of this type now search for all documents deposited in the corresponding collection and compare those that have the name value « ATS ». In our collection, this only concerns a single entry, so the output looks like this:
db.clients.find ( { "name" : "ATS" } )
{
"_id" : ObjectID ( "673d14684o75iftbb0ct5003" ),
"name" : "ATS",
"units" : 17,
"location" : "France",
"transactions" : {
"first" : {
"year" : 2021,
},
"last" : {
"year" : 2022,
},
"total" : 2
}
shell
The reverse method also works. If you want to display all results except the entry for « ATS », choose the next entry and you will get a very complete result again:
db.clients.find (
{ "name" : { $ne : "ATS" } }
)
shell
If you want to edit MongoDB queries with different values, this is possible with an array. In our example, we consider the customers « ATS » and « Jorgensen ».
db.clients.find (
{ "name" : [ $in : [ "ATS", "Jorgensen" ] } } }
)
shel
Querying multiple fields with MongoDB queries
To query multiple fields, it's important to specify your query further, especially if you need very specific results. That's why you can define MongoDB queries even more precisely by adding additional parameters. If we indicate for a query, in addition to the company name « ATS », the value of the segment « units », the system searches for a document that contains both values:
db.clients.find (
{ "name" : "ATS", "units" : 17 }
)
shell
Here, there is an exact match. But if one of the two values does not match, no results are displayed in this way. For example, the following entry would have no results:
db.client.find (
{ "name" : "ATS", "units" : 25 }
)
shell
If you want to consider different values with MongoDB Queries, but an input should already take place when at least one of the requirements is met, enter this:
db.clients.find (
{ $or : [ {"name" : "ATS"}, {"units" : 25 } ] }
)
shell
Query values in tables
Values in tables can also be taken into account with MongoDB queries. In our example, there are companies that have subsidiaries in several countries. If you want to edit all customers that have at least one branch in France, the entry is very simple:
db.clients.find (
{ "location" : "France" }
)
shell
The output now contains the three customers who have at least one branch in France. But if you want to expand your input and retrieve at the same time the customers who have branches in France and Belgium, use an array for this:
db.clients.find (
{ "location" : [ "France", "Belgium" ] }
)
shell
Note that MongoDB queries take into account the exact input and therefore, in this case, the order. If you want to take into account values regardless of their order in a table, complete the query like this:
db.clients.find (
{ "location" : { $all : [ "France", "Belgium" ] } }
)
shell
MongoDB Queries for Embedded Documents
In our example, we also used embedded documents. These can be edited with MongoDB queries. To do this, you need to add a dot to signal to MongoDB that the fields of an embedded document should be analyzed. For example, if you want to get a list of all customers who have more than ten orders, type this:
db.clients.find (
{ "transactions.total" : { $gt : 10 } }
)
shell
So MongoDB accesses the « transactions » document and then considers the number of orders under « total ».
MongoDB Queries: Limiting Output
With the methods seen so far, the output of MongoDB Queries can be very large. It can therefore be useful to limit the output to only a few fields. For this, we use so-called projections. These contain the value 1 (for the included fields) and 0 (for the fields that should be excluded). In the following example, we perform a two-part query. First, a search without parameters is launched, which would contain all the information. Right after, a projection is performed, which only takes into account the name field.
db.clients.find (
{ }
{ "name" : 1 } }
)
shell
So you get all the results, but the output is limited to names.
Use sliders to optimize output
Cursors are a method of not regulating the results of MongoDB queries themselves, but of adapting their rendering. You can, among other things, limit the number of results or change their order. If you only want to display a part of the results, use the limit method. It works like this:
db.clients.find (
{ }
{ "name" : 1 } }
).limit ( 2 )
shell
The following data allows you to reorganize the output. Thus, the three customers who ordered the least number of products will be displayed:
db.clients.find (
{ }
{ "name" : 1 } }
).limit ( 2 ) .sort ( { "units" : 1 } )
shell
Advice
To specifically find a document in your database, there is the MongoDB findONE method. We explain it in more detail in this article.