$add (aggregation)
On this page本页内容
Definition定义
$add-
Adds numbers together or adds numbers and a date. If one of the arguments is a date,将数字相加或将数字与日期相加。如果其中一个参数是日期,$addtreats the other arguments as milliseconds to add to the date.$add会将其他参数视为要添加到日期的毫秒。The$addexpression has the following syntax:$add表达式具有以下语法:{ $add: [ <expression1>, <expression2>, ... ] }The arguments can be any valid expression as long as they resolve to either all numbers or to numbers and a date.参数可以是任何有效的表达式,只要它们解析为所有数字或数字和日期即可。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。Starting in MongoDB 6.1 you can optimize the从MongoDB 6.1开始,您可以优化$addoperation.$add操作。To improve performance, group references at the end of the argument list. For example,为了提高性能,请在参数列表的末尾对引用进行分组。例如$add: [ 1, 2, 3, '$a', '$b', '$c' ]
Examples实例
The following examples use a 以下示例使用带有以下文档的sales collection with the following documents:sales集合:
{ "_id" : 1, "item" : "abc", "price" : 10, "fee" : 2, date: ISODate("2014-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "fee" : 1, date: ISODate("2014-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "fee" : 0, date: ISODate("2014-03-15T09:00:00Z") }
Add Numbers添加数字
The following aggregation uses the 以下聚合使用$add expression in the $project pipeline to calculate the total cost:$project管道中的$add表达式来计算总成本:
db.sales.aggregate(
[
{ $project: { item: 1, total: { $add: [ "$price", "$fee" ] } } }
]
)
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "item" : "abc", "total" : 12 }
{ "_id" : 2, "item" : "jkl", "total" : 21 }
{ "_id" : 3, "item" : "xyz", "total" : 5 }
Perform Addition on a Date在某个日期执行添加
The following aggregation uses the 以下聚合使用$add expression to compute the billing_date by adding 3*24*60*60000 milliseconds (i.e. 3 days) to the date field :$add表达式通过将3*24*60*60000毫秒(即3天)添加到日期字段来计算billing_date:
db.sales.aggregate(
[
{ $project: { item: 1, billing_date: { $add: [ "$date", 3*24*60*60000 ] } } }
]
)
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "item" : "abc", "billing_date" : ISODate("2014-03-04T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "billing_date" : ISODate("2014-03-04T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "billing_date" : ISODate("2014-03-18T09:00:00Z") }