mongoose find one

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

MongoDB provides several methods to perform a Read operation on a collection. All these methods are supported by mongoose also. Some of the common methods are find(), findOne(), findOneAndUpdate(), and findOneAndDelete(). Each of these methods has unique functionality. We can use them according to our requirements. In this article, our focus is on the findOne() method. As the name suggests, the findOne() method retrieves a single document from a MongoDB collection. Let’s discuss the mongoose find one method using examples.

We will use the myteam collection for demonstration.

1
2
3
4
5
{ "_id" : ObjectId("5e463e67e6f8b824961e87cc"), "name" : "Leonel Messi", "club" : "Barcelona", "country" : "Argentina" }
{ "_id" : ObjectId("5e463ea3e6f8b824961e87cd"), "name" : "Cristiano Ronaldo ", "club" : "Juventis", "country" : "Portugal" }
{ "_id" : ObjectId("5e463eb3e6f8b824961e87ce"), "name" : "Neymar", "club" : "PSG", "country" : "Brazil" }
{ "_id" : ObjectId("5e463ecee6f8b824961e87cf"), "name" : "Sergio Ramos", "club" : "Real Madrid", "country" : "Spain" }
{ "_id" : ObjectId("5e463ef9e6f8b824961e87d0"), "name" : "Marc-Andre ter Stegen", "club" : "Barcelona", "country" : "Germany" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

findOne()

As mentioned earlier, the findOne() method returns a single document. Now there can be two cases with the findOne() method:

  1. When a query is provided, the findOne() method will match a single document. All other documents that can match the query will be ignored and the findOne() method will return only the very first document that can match.

  2. If there is no query provided, the findOne() method will return the very first document of the collection.

We will discuss both these cases in this article. Let’s start by creating a route handler.

1
router.route("/findone").get(function(req, res) {});

The above route handler will be invoked when the endpoint ‘/findOne’ is executed. Let’s add a findOne() method in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
router.route('/findone').get(function(req,res){

    myteam.findOne( ,function(err, result){

        if(err){
            res.send(err)
        }
        else{
            res.json(result)
        }

    })


})

Currently, the query part is empty. So it won’t run. Observe the following.

1
{"name" : "Neymar"}

If we will provide the above as the query to the findOne() method, it will return the document where the value of the name field is “Neymar”. Let’s do this.

1
2
3
4
5
6
7
8
9
router.route("/findone").get(function(req, res) {
  myteam.findOne({ name: "Neymar" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

We can see it successfully returns the document where the value of the name field is “Neymar”. There is only one such document that can match the query. What if multiple documents can match the query? Let’s try it out.

1
{"club" : "Barcelona"}

Observe the myteam collection.

1
2
3
4
5
{ "_id" : ObjectId("5e463e67e6f8b824961e87cc"), "name" : "Leonel Messi", "club" : "Barcelona", "country" : "Argentina" }
{ "_id" : ObjectId("5e463ea3e6f8b824961e87cd"), "name" : "Cristiano Ronaldo ", "club" : "Juventis", "country" : "Portugal" }
{ "_id" : ObjectId("5e463eb3e6f8b824961e87ce"), "name" : "Neymar", "club" : "PSG", "country" : "Brazil" }
{ "_id" : ObjectId("5e463ecee6f8b824961e87cf"), "name" : "Sergio Ramos", "club" : "Real Madrid", "country" : "Spain" }
{ "_id" : ObjectId("5e463ef9e6f8b824961e87d0"), "name" : "Marc-Andre ter Stegen", "club" : "Barcelona", "country" : "Germany" }

We can see two documents can match the query. What will the findOne() return? Let’s see.

1
2
3
4
5
6
7
8
9
router.route("/findone").get(function(req, res) {
  myteam.findOne({ club: "Barcelona" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

It returns only a single document. But there we two documents that can match the query, right? The findOne() method returns only the first document that matches the query.

Now, what if we don’t provide any query? Just an empty object. What will happen then? Let’ see.

1
2
3
4
5
6
7
8
9
router.route("/findone").get(function(req, res) {
  myteam.findOne({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

As mentioned earlier, it returns the very first document in the collection.

Conclusion

So the findOne() method is used to retrieve a single document from a collection. It is simple and easy to use. But it is a perfect choice when multiple documents can match the query but we need only the first of them.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.