mongoose push

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

Introduction

There are several data structures such as trees, graphs, arrays, stacks, etc. Arrays are one of the most commonly used data structures in the programming world. They are perfect to store values. We can store any type of data in arrays. While working with databases, we may need to store data in an array. For example, the following MongoDB documents contain a field that stores an array of Strings.

1
2
3
{
    "Clubs" : ["Sporting"]
}

So the “clubs” array has only one value. We may need to update this array, right? We may need to add more values in it or remove values from it. Mongoose provides a few ways for this. We can use any of the Update method such as updateOne() and updateMany(). But to add or remove values from an array in mongoose, we have special operators. These operators are $push and $pop, respectively. In this article, we will discuss how to use the mongoose $push operator to insert values in an array.

We will use the football collection.

1
2
3
{ "_id" : ObjectId("5e4a44abd777270ee458b9e8"), "name" : "Leonel Messi", "clubs" : [ "Barcelona" ] }
{ "_id" : ObjectId("5e4a4501d777270ee458b9e9"), "name" : "Cristiano Ronaldo", "clubs" : [ "Sporting" ] }
{ "_id" : ObjectId("5e4a4538d777270ee458b9ea"), "name" : "Neymar", "clubs" : [ "Santos", "Barcelona", "PSG" ] }

There are three documents in this collection. Each document has two fields – name and clubs (and _id field of course). The clubs field has an array of string as its value. Observe the document where the value of the name field is “Cristiano Ronaldo”.

1
{ "_id" : ObjectId("5e4a4501d777270ee458b9e9"), "name" : "Cristiano Ronaldo", "clubs" : [ "Sporting" ] }

In this document, the array has only one value. But Cristiano Ronaldo had played for three more clubs – Manchester United, Real Madrid, and Juventis. So in this article, we will use the $push operator to insert these three values in this document’s clubs field.

We will use the postman tool for testing. You can download it from www.getpostman.com.

$push operator

Let’s start by creating a route handler.

1
router.route("/update").put(function(req, res) {});

To update a single document, mongoose provides the updateOne() method. Let’s add it to the route handler.

1
2
3
4
5
6
7
8
9
router.route("/update").put(function(req, res) {
  players.updateOne({}, {}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Currently, we are passing empty objects as a query as well as the update. The following query will do the job.

1
{ "name" : "Cristiano Ronaldo"}

We have to add three values to the array. First, we will add one value, say Manchester United.

1
{$push" : { clubs : ["Manchester United"]}}

This is how we use the $push operator. Let’s add all these to the updateOne() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/update").put(function(req, res) {
  players.updateOne(
    { name: "Cristiano Ronaldo" },
    { $push: { clubs: ["Manchester United"] } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
    }
  );
});

Now we can execute this route using the postman tool.

Image from Gyazo

The updateOne() method returns an object. We can check through the mongo shell if the value was inserted or not.

Image from Gyazo

Yes! The value is inserted.

We inserted a single value. We can also insert multiple values using the $push operator. Two values, “Real Madrid” and “Juventis” are yet to be inserted. So let’s do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/update").put(function(req, res) {
  players.updateOne(
    { name: "Cristiano Ronaldo" },
    { $push: { clubs: ["Real Madrid", "Juventis"] } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
    }
  );
});

Image from Gyazo

Let’s verify using the mongo shell.

Image from Gyazo

Yes! It worked perfectly.

Conclusion

Arrays are fairly used in MongoDB. They are very useful data structures that can store multiple values. Mongoose provides several operators that could be used with arrays. The $push operator is one of them that we discussed in this article.

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.