2 Ways to Append a Value to an Array in MongoDB

If you have a collection of documents in MongoDB that contain arrays, you can add new values to those arrays if required.

Depending on your specific requirements, you can use the $push operator or the $addToSet operator.

The $push Operator

Suppose we have a collection called products with the following documents:

{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 3, "product" : "Cap", "sizes" : [ "M", "L" ] }

And let’s say we want to append a value to the array in document 3.

We can use $push in conjunction with update() to append the value:

db.products.update(
   { _id: 3 },
   { $push: { sizes: "XL" } }
)

Let’s look at the collection again to verify the change:

db.products.find()

Result:

{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 3, "product" : "Cap", "sizes" : [ "M", "L", "XL" ] }

We can see that the value XL has been added to the array in document 3.

The $push operator can also be used with various modifiers, such as $position, $sort, and $slice.

You can also add multiple values to the array by using the $each modifier.

See MongoDB $push for examples.

The $addToSet Operator

The $addToSet operator works in a similar way to $push, except for a couple of things:

  • If the value you’re trying to add already exists in the array, it won’t be added.
  • The $position, $sort, and $slice modifiers can’t be used with $addToSet.

Suppose our collection looks like this:

{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 3, "product" : "Cap", "sizes" : [ "S", "M", "L", "XL" ] }

Let’s insert multiple values to the array in document 2:

db.products.update(
   { _id: 2 },
   { 
     $addToSet: { 
        sizes: {
           $each: [ "XXL", "XXXL" ]
        }
      } 
    }
)

Now let’s check the collection again:

db.products.find()

Result:

{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL", "XXL", "XXXL" ] }
{ "_id" : 3, "product" : "Cap", "sizes" : [ "S", "M", "L", "XL" ] }

We can see that the two values were appended to the array in document 2 as expected.

This example uses the $each modifier, which you can also use with the $push operator.

I only used the $each modifier because I was adding multiple values. If I was only using one value, I could have omitted the $each modifier, and the syntax would have looked more like the above $push example.

As mentioned, if the value already exists, it won’t be added. Also, with both operators, if you add an array, the whole array will be added as a separate value within the existing array.

See MongoDB $addToSet for more examples.