AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

MongoDB findOne: user guide

PARTAGEZ

The MongoDB findOne method is very effective for searching within a collection. However, it only returns one result at a time, so it may not be suitable for all needs.

What is MongoDB findOne?

MongoDB is a database management system that, thanks to its NoSQL approach and high scalability, can easily store and manage large amounts of data. This is certainly a great advantage, but it requires solid methods for users to keep an overview when working with the database.

The system stores data of all types as a BSON (Binary JSON) document and groups these documents into collections. If you want to search for and edit one of these documents, you have several options. In addition to the more general MongoDB find method, MongoDB findOne is a method very effective to filter even large databases in a targeted manner.

MongoDB findOne searches all documents and collections considered according to certain criteria that can be specified by the user. The special feature of this method is that it returns only one document matching the specified parameters. If only one document appears in the search request, that document is considered. If multiple documents are considered, MongoDB findOne displays the document that appears first in the natural order of the database. If no documents can be found in the search, the result is “zero”.

MongoDB findOne Syntax and Peculiarities

The basic syntax of MongoDB findOne is very clear. The method is always applied in the following way:

db.collection.findOne ( , ,  )

shell

Below the search parameters by which the method should filter documents are specified. This entry is optional. The entries under determine which fields are taken into account for the displayed document. The allowed values ​​for the output are the Boolean values ​​1 (respectively true) and 0 (respectively false). If this indication remains empty, all fields are always displayed. It is therefore also optional. allows you to modify the search and change the display.

Note

To perform efficient searches in collections with multiple search parameters, there are MongoDB Queries, which we will explain in more detail in another article. Queries are based on the MongoDB find command.

Create a collection for testing purposes

If you have installed MongoDB on Linux, Windows or Mac and want to use MongoDB findOne for yourself, it is worthwhile to first create a test environment for the first use of the method. We show you the first steps with the database in our very comprehensive MongoDB tutorial. For our example, we imagine an employee database that contains five entries and information about the name, gender and age of the employee. There is also information about the date the person joined the company. This collection looks like this, for example:

db.collaborateurs.insertMany ( [
    {
    name : "Martin",
    gender : "Female",
    age : 56,
    year : 2002
    },
    {
    name : "Lejeune",
    gender : "Female",
    age : 40,
    year : 2017,
    },
    {
    name : "Foucault",
    gender : "Male",
    age : 40,
    year : 2019
    },
    {
    name : "Arslan",
    gender : "Female",
    age : 44,
    year : 2015
    },
    name : "Jacob",
    gender : "Male",
    age : 22,
    year : 2022
    }
]
)

shell

MongoDB findOne: search without parameters

If you apply the MongoDB findOne method in this example without any parametersthe system will search your database and find five entries that it should consider. Since no documents are excluded, all five collaborators are considered. As a result, MongoDB findOne would select the first person that was entered into the database, since the method only plays one result at a time. Here is the result for our example:

db.collaborateurs.findOne ( )

shell

Here is the corresponding output:

db.collaborateurs.findOne ( )
{
    _id : ObjectID ( "529ete7300of4002bme148om" ),
    name : "Martin",
    gender : "Female",
    age : 56,
    year : 2002
}

shell

Search entries by ID

MongoDB findOne provides the right tools to perform a specific search to find exactly the document you need. A very safe method is searching by ID. The _id field is unique in each document and can therefore always be assigned exactly one collaborator, in the case of our example. If you run MongoDB findOne via the object ID, you will get the exact result. Here is a scenario with our previous example:

db.collaborateurs.findOne ( { _id : ObjectID ( "582pfh773813tw982qj411l0" ) } )

shell

The output should then be as follows:

db.collaborateurs.findOne ( { _id : ObjectID ( "582pfh773813tw982qj411l0" ) } )
{
    _id : ObjectID ( "582pfh773813tw982qj411l0"
    name : "Jacob",
    gender : "Male",
    age : 22,
    year : 2022
}

shell

Search for specific fields with MongoDB findOne

If you don't know the ID or want to search for other parameters in your collection, you can also search special fields with MongoDB findOne. Here too, if there is only one document matching the parameter, it will be displayed. However, if multiple documents match your search criteria, the system will only display the first entry. In our example, we are therefore looking for all entries whose gender is “Male”. In theory, the output would consist of two results. But only the first one will be displayed. Here is how the corresponding command works:

db.collaborateurs.findOne ( { gender : "Male" } )

shell

The output then shows the employee Mr. Foucault:

db.collaborateurs.findOne ( { gender : "Male" } )
{
    _id : ObjectID ( "498p0t173mv489fh63th00kh"
    name : "Foucault",
    gender : "Male",
    age : 40,
    year : 2019
}

shell

MongoDB findOne: Specify the search

Of course, you also have the option to limit your search to avoid any overlap. In our small collection of examples, this is not necessarily necessary, but if you are working with several hundred or thousands of entries, you will appreciate this option. MongoDB findOne allows you to use multiple fields for searching. Here's what it looks like if you want to identify an employee based on their gender (male) and age:

db.collaborateurs.findOne ( { gender : "Male", age: 40 } )

shell

The exit then shows Mr. Foucault again, who is the only person in the collection who is a man and is 40 years old. The employee Mrs. Lejeune would certainly have been the same age, but she is female.

db.collaborateurs.findOne ( { gender : "Male", age: 40 } )
{
    _id : ObjectID ( "498p0t173mv489fh63th00kh"
    name : "Foucault",
    gender : "Male",
    age : 40
    year : 2019
}

shell

Define conditions for a field

It is also possible to define conditions for a specific field and apply them as search criteria. In the following example, we only consider people over 30 years old.

Here is the entry:

db.collaborateurs.findOne ( { age : { $gt : 30 } } )

shell

So, the collaborator Mr. Jacob is excluded. Since Mrs. Martin matches the criteria and is the first person in the list, she is displayed again:

db.collaborateurs.findOne ( { age : { $gt : 30 } } )
{
    _id : ObjectID ( "529ete7300of4002bme148om" ),
    name : "Foucault",
    gender : "Female",
    age : 56,
    year : 2002
}

shell

Exclude fields with MongoDB findOne

Especially in the case of large collections, which also contain a lot of information, the output can become confusing. That is why MongoDB findOne offers the possibility to exclude individual fields for output. In the following example, we want ID, gender and age not to be displayed.

db.collaborateurs.findOne ( { name : "Martin" }, { _id : 0, gender : 0, age : 0 } )

shell

As all other data is displayed, you get the following output:

db.collaborateurs.findOne ( {name : "Martin" }, { _id : 0, gender : 0, age : 0 } )
{
    name : "Martin",
    year : 2002
}

shell

Example of unsuccessful search

If there are no results for your search with MongoDB findOne, this will be indicated to you. So we are looking for the collaborator Ferrier who is not mentioned in the collection.

db.collaborateurs.findOne ( { name : "Ferrier" } )

shell

The output is then as follows:

db.collaborateurs.findOne ( { name : "Ferrier" } )
null

shell

Advice

To manage your database more easily, there is a free graphical interface MongoDB Compass, which we will present in another article.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact