Using $each Operator in MongoDB (With $addToSet & $push)

In MongoDB, we store data in the form of documents. These documents may contain arrays or embedded arrays as field values. Suppose you have a big collection of records where you have millions of documents and in each of them there are lots of fields, among them some might be array fields containing an array or some might contain nested documents that may have their own arrays.

In this type of complicated structure, how hard it becomes to perform operations on these arrays manually. Here MongoDB shows its power and provides various operators that can perform operations on an array within documents or nested documents.

One famous operator that we have already talked about is the $pullAll operator which is used to pull or remove values from the array. But what if we want to add value? Well, here comes the $push operator. But $push by itself can only push a single element at a time. So what is the solution? Presenting the $each operator.

In this article, we will look at detailed information about the $each operator, and its syntax and demonstrate it with the $addToSet and $push operators. Let’s get started.

MongoDB $each Operator

The $each operator can be used with either the $addToSet or $push operator to add, append or we can say insert multiple elements into an array. This does not mean that $each gives the same result with each of them. There are minor differences in their functionality which we will discuss in the next section.

MongoDB $each Operator with $addToSet

The $each operator when used with $addToSet can act as a modifier by which we can add multiple values to a specific array, tossing the values it is adding if it has duplicates i.e. it only adds unique values to the array. In simple words, $addToSet can insert multiple elements into an array ensuring that duplicates are not inserted.

Syntax:

db.collection.updateMany({}, { $addToSet: { field: { $each: [ value1, value2 ... ] } } })

Parameters:

  1. Here “collection” is the collection name where we are looking for the documents.
  2. “updateMany()” is the method we are using to update the documents.
  3. In “{ field1: [ value1, value2 … ], … }”, the field represents an array field within the documents, and [ value 1, value 2 …. ] are the elements we want to insert into that array field.

Read more about $addToSet operator: Ultimate Guide to Using $addToSet Operator in MongoDB

MongoDB $each Operator with $push

The $each operator, when used with $push, can add multiple values to a specified array, without tossing duplicates i.e. it also adds duplicate values to the array.

You can use $each operator with $push where need to insert values in an array even if they are duplicates, which is in most of the cases.

Syntax:

db.collection.updateMany({}, { $push: { field: { $each: [ value1, value2 ... ] } } })

Parameters:

  1. Here “collection” is the collection name where we are looking for the documents.
  2. “updateMany()” is the method we are using to update the documents.
  3. In “{ field1: [ value1, value2 … ], … }”, the field represents an array field within the documents, and [ value 1, value 2 …. ] are the elements we want to insert into that array field.

Read more about $push operator: $push Operator in MongoDB – Ultimate Beginner’s Guide

Examples of Using $each Operator in MongoDB 

Let us start by using the $each operator with the $addToSet & $push operator to add elements in an array within documents.

Setup:

1. Start the MongoDB shell.

2. Execute the below command to list all the available databases.

show dbs

 3. Use the below command to move into one of them.

use droneShop

Here we are using the “droneShop” database where we have already created a collection “drones” having documents containing an array field so that we can demonstrate removing elements using the $each operator.

Following are the documents inside “drones”:

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("61573946341d653bccaf7827"),
        "utility" : [
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography"
        ],
        "onSale" : false,
        "name" : "Thunderbird Phoenix ",
        "price" : 2000,
        "weight" : "1.7 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615739bb341d653bccaf7828"),
        "utility" : [
                "Delivery",
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography"
        ],
        "onSale" : false,
        "name" : "FR - Hummingbird",
        "price" : 2000,
        "weight" : "20 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f092d0a441e040c3fdc"),
        "utility" : [
                "Photography",
                "Monitoring or Inspection",
                "Security",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Dixy Magenta",
        "price" : 2000,
        "weight" : "4.7 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f6e2d0a441e040c3fdd"),
        "utility" : [
                "Photography",
                "Monitoring or Inspection",
                "Security",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "UJ - Spear Eye Forest Green",
        "price" : 2000,
        "weight" : "3 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61598fe5ebf45d32b85bd1a3"),
        "utility" : [
                "Security",
                "Monitoring or Inspection",
                "Recreation",
                "Photography"
        ],
        "onSale" : false,
        "name" : "Golden Pegasus 57B",
        "price" : 2000,
        "weight" : "5 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61599147ebf45d32b85bd1a4"),
        "utility" : [
                "Security",
                "Monitoring or Inspection",
                "Recreation",
                "Photography"
        ],
        "onSale" : false,
        "name" : "P12 - Mercenary SF",
        "price" : 2000,
        "weight" : "2 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615991e9ebf45d32b85bd1a6"),
        "utility" : [
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography"
        ],
        "onSale" : false,
        "name" : "Meteor Rada W54",
        "price" : 2000,
        "weight" : "7 kilograms",
        "__v" : 0
}

If you are wondering why we have used  pretty() function, it is used here to format the output with a proper indentation and increase readability making documents easier to view and understand.

Using $each Operator with $addToSet

Let’s now try to use the $each operator with $addToSet and specify an array having some elements to be added to the “utility” array field in the above documents.

Below is the query for the same:

> db.drones.updateMany( {}, { $addToSet: { utility: { $each: [ "Videography", "Combat", "Rescue", "Construction" ] } } } )

{ "acknowledged" : true, "matchedCount" : 7, "modifiedCount" : 7 }

Let’s see what the documents look like now:

> db.drones.find({}).pretty()
{
        "_id" : ObjectId("61573946341d653bccaf7827"),
        "utility" : [
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Thunderbird Phoenix ",
        "price" : 2000,
        "weight" : "1.7 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615739bb341d653bccaf7828"),
        "utility" : [
                "Delivery",
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "FR - Hummingbird",
        "price" : 2000,
        "weight" : "20 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f092d0a441e040c3fdc"),
        "utility" : [
                "Photography",
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Dixy Magenta",
        "price" : 2000,
        "weight" : "4.7 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f6e2d0a441e040c3fdd"),
        "utility" : [
                "Photography",
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "UJ - Spear Eye Forest Green",
        "price" : 2000,
        "weight" : "3 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61598fe5ebf45d32b85bd1a3"),
        "utility" : [
                "Security",
                "Monitoring or Inspection",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Golden Pegasus 57B",
        "price" : 2000,
        "weight" : "5 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61599147ebf45d32b85bd1a4"),
        "utility" : [
                "Security",
                "Monitoring or Inspection",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "P12 - Mercenary SF",
        "price" : 2000,
        "weight" : "2 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615991e9ebf45d32b85bd1a6"),
        "utility" : [
                "Monitoring or Inspection",
                "Security",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Meteor Rada W54",
        "price" : 2000,
        "weight" : "7 kilograms",
        "__v" : 0
}

Using $each Operator with $push

Let’s now try to use the $each operator with $push and specify an array having some elements to be added to the “utility” array field in the above documents.

Below is the query for the same:

> db.drones.update( { name: `Golden Pegasus 57B` }, { $push: { utility: { $each: [ `Bulky`, `Heavy`, `Lightweight` ] } } } )

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Let’s see what the document looks like now which we just updated:

> db.drones.find( { name: `Golden Pegasus 57B` } ).pretty()

{
        "_id" : ObjectId("61598fe5ebf45d32b85bd1a3"),
        "utility" : [
                "Security",
                "Monitoring or Inspection",
                "Recreation",
                "Photography",
                "Videography",
                "Combat",
                "Rescue",
                "Construction",
                "Bulky",
                "Heavy",
                "Lightweight"
        ],
        "onSale" : false,
        "name" : "Golden Pegasus 57B",
        "price" : 2000,
        "weight" : "5 kilograms",
        "__v" : 0
}

This way we have successfully learned to use the $each operator with the $addToSet operator and the $push operator in MongoDB.

Conclusion

In this article, we have explored the $each operator, its syntax and examples. We learned that when we have to insert multiple elements into an array, guaranteeing that duplicates are not inserted, we can use the $addToSet operator and when we have to insert values into an array, even if they are duplicates, we can use the $push operator. We hope that we were able to address all your questions and provide the answers you’re looking for.

References

Aneesha S
Aneesha S
Articles: 171