MongoDB $subtract 运算符2024 年 9 月 6 日 | 阅读 4 分钟 MongoDB 提供了各种算术表达式运算符。$subtract 运算符是这些运算符之一。此运算符用于减去两个数字或日期,并返回差值。
$subtract 运算符的语法注意:参数必须是有效的表达式,例如数字或日期。在此运算符中,第二个参数减去第一个参数。如果您想从日期中减去一个数字,则第一个参数应始终为日期。示例假设我们有一个包含以下文档的学生集合。 示例 1:使用 $subtract 运算符减去两个数字 在此示例中,我们将使用 $subtract 运算符从 annual_fee 字段中减去 semester_fee 字段。 输出 { "_id" : 1, "std_name" : "John", "father_name" : "Mick", "semester_fee" : 6000, "annual_fee" : 10000, "result" : 4000 } { "_id" : 3, "std_name" : "Jack", "father_name" : "James", "semester_fee" : 7000, "annual_fee" : 12500, "result" : 5500 } { "_id" : 6, "std_name" : "Daniel", "father_name" : "Paul", "semester_fee" : 12500, "annual_fee" : 25000, "result" : 12500 } 示例 2:使用 $subtract 运算符减去两个日期 在此示例中,我们将使用 $subtract 运算符从 "end_date" 字段中减去 "start_date" 字段。 输出 { "_id" : 2, "std_name" : "Oliver", "father_name" : "Thomas", "start_date" : ISODate("2020-07-03T08:00:00Z"), "end_date" : ISODate("2023-05-01T09:00:00Z"), "result" : NumberLong("18644531576187") } { "_id" : 5, "std_name" : "Richard", "father_name" : "William", "start_date" : ISODate("2019-07-03T08:00:00Z"), "end_date" : ISODate("2022-05-01T09:00:00Z"), "result" : NumberLong("18644531576187") } 示例 3:使用 $subtract 运算符从日期中减去一个数字 在此示例中,我们将使用 $subtract 运算符从 "start_date" 字段中减去 250。 输出 { "_id" : 3, "std_name" : "Jack", "father_name" : "James", "department" : "MCA", "start_date" : ISODate("2020-07-11T00:00:00Z"), "result" : ISODate("2020-07-10T23:59:59.750Z") } 我们可以看到,250 毫秒已从 "start_date" 字段中减去。 如果我们更改参数的位置会发生什么? 输出 uncaught exception : Error : command failed : { "ok": 0, "errmsg": "cant $subtract a date from a double", "code": 16556, "codeName": "Location16556" } : aggregate failed: _getErrorWithCode@src/mongo/shell/utils.js : 25 : 13 doassert@src/mongo/shell/assert.js : 18 : 14 _assertCommandWorked@src/mongo/shell/assert.js : 618 : 17 assert.commandWorked@src/mongo/shell/assert.js : 708 : 16 DB.prototype._runAggregate@src/mongo/shell/db.js : 266 : 5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js : 1046 : 12 @(shell) : 1 : 1 正如您所看到的,如果第一个参数是数字,第二个参数是日期,则会收到错误。 |
我们请求您订阅我们的新闻通讯以获取最新更新。