mongoose Query Example

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

Introduction

There is a vast range of methods as well as operators in mongoose that could be used on MongoDB collections. Each of these methods and operators has its own specialty. In this article, we will focus on the query part of these methods and we will also discuss some of the operators.

For performing this mongoose query example, we will use the postman tool. You can download the postman tool from www.getpostman.com.

insertMany()

So let’s start by inserting some documents in a collection. We have an empty collection named myteam. We will add three documents in it using the insertMany() method. But first, let’s create a route handler.

1
router.route("/demo").post(function(req, res) {});

We have to add three documents in the collection. The insertMany() method takes an array of objects as its first argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
router.route("/demo").post(function(req, res) {
  myteam.insertMany(
    [
      {
        name: "Leonel Messi",
        Country: "Argentina"
      },
      {
        name: "Cristiano Ronaldo",
        Country: "Portugal"
      },
      {
        name: "Neymar",
        Country: "Brazil"
      }
    ],
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
    }
  );
});

The query part contains an array of objects(documents). Let’s execute this route using the postman tool.

Image from Gyazo

Yes! All three documents are inserted into the collection. The insertMany() method returns those documents that are inserted in the collection. Next, we will discuss the method to read this collection.

find()

We have documents inserted in the myteam collection. Let’s retrieve them using the find() method.

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

Observe the query part of the find() method. It is an empty object. This means it will retrieve all the documents of the myteam collection. Let’s try.

Image from Gyazo

It works perfectly. There are few other methods such as findOne() and findById().

$in

Let’s discuss one of the most common operators that are used in the query – $in operator. Suppose we only need those documents where the value of the country field is either “Portugal” or “Brazil”. Well, there are a couple of ways do to this, but we will focus on the $in operator.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/demo").get(function(req, res) {
  myteam.find({ country: { $in: ["Portugal", "Brazil"] } }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

The $in operator takes an array as its value. It will match all those documents where the value of the country field matches any of the values that are present in the array. Let’s execute this route.

Image from Gyazo

Yes! only those documents are present where the value of the country field is either “Portugal” or “Brazil”.

deleteOne()

Let’s delete one document using the deleteOne() method.

1
2
3
4
5
6
7
8
9
router.route("/demo").delete(function(req, res) {
  myteam.deleteOne({ name: "Cristiano Ronaldo" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Let’s execute this route.

Image from Gyazo

It returns an object. The “deletedCount” is equal to 1. This means, one document was deleted from the collection. The deleteOne() matches and deletes only a single document.

updateOne()

The updateOne() method updates a single document.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/demo").put(function(req, res) {
  myteam.updateOne(
    { name: "Leonel Messi" },
    { $set: { country: "Spain" } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
    }
  );
});

The updateOne() method has two arguments. The first is the query that will match a document and the second is the update itself. Observe the second one.

1
{$set : { "country" : "Spain"}}

Well, this does not make sense because Leonel Messi plays for Argentina. Never mind! Here, we used the $set operator. Let’s execute this route.

Image from Gyazo

It returns an object. The value of the “nModified” is 1. This means one document was updated. Let’s verify through the mongo shell.

1
2
3
> db.myteam.find()
{ "_id" : ObjectId("5e3156384cebc26c984ce9ee"), "name" : "Leonel Messi", "country" : "Spain", "__v" : 0 }
{ "_id" : ObjectId("5e3156384cebc26c984ce9f0"), "name" : "Neymar", "country" : "Brazil", "__v" : 0 }

Yes! The value is changed to “Spain” from “Argentina”.

Conclusion

So these were few methods and operators that are commonly used in mongoose. I tried to keep it simple with very easy examples.

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.