$subtract (aggregation)

On this page本页内容

Definition定义

$subtract

Subtracts two numbers to return the difference, or two dates to return the difference in milliseconds, or a date and a number in milliseconds to return the resulting date.减去两个数字以返回差值,或两个日期以毫秒为单位返回差值,或一个日期和一个数字以毫秒为单位返回结果日期。

The $subtract expression has the following syntax:语法如下所示:

{ $subtract: [ <expression1>, <expression2> ] }

The second argument is subtracted from the first argument.从第一个参数中减去第二个参数。

The arguments can be any valid expression as long as they resolve to numbers and/or dates. 参数可以是任何有效的表达式,只要它们解析为数字和/或日期。To subtract a number from a date, the date must be the first argument. 要从日期中减去一个数字,日期必须是第一个参数。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Examples示例

Consider a sales collection with the following documents:考虑一个sales集合带有以下文档:

db.sales.insertMany([
   { "_id" : 1, "item" : "abc", "price" : 10, "fee" : 2, "discount" : 5, "date" : ISODate("2014-03-01T08:00:00Z") },
   { "_id" : 2, "item" : "jkl", "price" : 20, "fee" : 1, "discount" : 2, "date" : ISODate("2014-03-01T09:00:00Z") }
])

Subtract Numbers数字相减

The following aggregation uses the $subtract expression to compute the total by subtracting the discount from the subtotal of price and fee.以下聚合使用$subtract表达式,通过从pricefee小计中减去discount来计算total

db.sales.aggregate( [ { $project: { item: 1, total: { $subtract: [ { $add: [ "$price", "$fee" ] }, "$discount" ] } } } ] )

The operation returns the following results:操作返回以下结果:

{ "_id" : 1, "item" : "abc", "total" : 7 }
{ "_id" : 2, "item" : "jkl", "total" : 19 }

Subtract Two Dates两个日期相减

The following aggregation uses the $subtract expression to subtract $date from the current date, using the system NOW (available starting in 4.2) and returns the difference in milliseconds:下面的聚合使用$subtract表达式从当前日期减去$date,使用系统NOW(从4.2开始提供)并以毫秒为单位返回差值:

db.sales.aggregate( [ { $project: { item: 1, dateDifference: { $subtract: [ "$$NOW", "$date" ] } } } ] )

Alternatively, you can use the Date() for the current date:或者,您可以将Date()用于当前日期:

db.sales.aggregate( [ { $project: { item: 1, dateDifference: { $subtract: [ new Date(), "$date" ] } } } ] )

Both operations return documents that resemble the following:这两个操作返回的文档类似于以下内容:

{ "_id" : 1, "item" : "abc", "dateDifference" : NumberLong("186136746187") }
{ "_id" : 2, "item" : "jkl", "dateDifference" : NumberLong("186133146187") }

Subtract Milliseconds from a Date从日期中减去毫秒

The following aggregation uses the $subtract expression to subtract 5 * 60 * 1000 milliseconds (5 minutes) from the “$date” field:以下聚合使用$subtract表达式从“$date”字段中减去5*60*1000毫秒(5分钟):

db.sales.aggregate( [ { $project: { item: 1, dateDifference: { $subtract: [ "$date", 5 * 60 * 1000 ] } } } ] )

The operation returns the following results:操作返回以下结果:

{ "_id" : 1, "item" : "abc", "dateDifference" : ISODate("2014-03-01T07:55:00Z") }
{ "_id" : 2, "item" : "jkl", "dateDifference" : ISODate("2014-03-01T08:55:00Z") }