Introduction to MongoDB $add Operator

The MongoDB $add operator can be used to add multiple numbers together and can accept any number of arguments. The $add operator is commonly used in aggregation pipelines for scenarios such as calculating total price and score.

Syntax

The syntax of the $add operator is as follows:

{ $add: [ <expression1>, <expression2>, ... ] }

Here, <expression> is any expression, which can be a number, field, arithmetic expression, etc. The $add operator adds all expressions together and returns the result.

Use Cases

The $add operator is commonly used in the $project, $group, and $addFields stages of an aggregation pipeline to add multiple expressions together and generate new fields or values.

Examples

Example 1: Calculate the total sales value of each product

Suppose there is a collection of sales records that includes the product name, sales quantity, and sales amount. Now we want to calculate the total sales value of each product. Here is the query:

db.sales.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      totalValue: { $add: [{ $multiply: ["$qty", "$price"] }] }
    }
  }
])

Here is the result:

{ "name" : "A", "totalValue" : 100 }
{ "name" : "B", "totalValue" : 50 }
{ "name" : "C", "totalValue" : 60 }
{ "name" : "D", "totalValue" : 85 }
{ "name" : "E", "totalValue" : 95 }

Example 2: Calculate the time difference between two time fields

Suppose there is a collection of user login records that includes the user ID, login time, and logout time. Now we want to calculate the login duration of each user. Here is the query:

db.logins.aggregate([
  {
    $project: {
      _id: 0,
      userId: 1,
      timeDiff: {
        $divide: [{ $subtract: ["$logoutTime", "$loginTime"] }, 1000 * 60]
      }
    }
  },
  {
    $group: {
      _id: "$userId",
      totalLoginTime: { $add: "$timeDiff" }
    }
  }
])

Here is the result:

{ "_id" : 1001, "totalLoginTime" : 140 }
{ "_id" : 1002, "totalLoginTime" : 192 }
{ "_id" : 1003, "totalLoginTime" : 98 }
{ "_id" : 1004, "totalLoginTime" : 116 }
{ "_id" : 1005, "totalLoginTime" : 184 }
{ "_id" : 1006, "totalLoginTime" : 132 }
{ "_id" : 1007, "totalLoginTime" : 94 }
{ "_id" : 1008, "totalLoginTime" : 108 }
{ "_id" : 1009, "totalLoginTime" : 122 }
{ "_id" : 1010, "totalLoginTime" : 90 }

Conclusion

The $add operator can be used to add multiple numbers together and can accept any number of arguments. The $add operator has many use cases in aggregation pipelines, such as calculating total price and score.