MongoDB $mod 运算符2024 年 9 月 6 日 | 3 分钟阅读 什么是 $mod 运算符?MongoDB 提供了各种算术表达式运算符。$mod 运算符是这些运算符之一。$mod 运算符用于聚合管道阶段。$mod 运算符用于将一个数字除以另一个数字并返回余数。换句话说,第一个数字是被除数,第二个数字是除数。 $log 运算符的语法那个 (The) 示例在下面的示例中,我们将使用 >db.items.find().pretty()
{
{
"_id" : 1,
"item_name" : "Apple",
"total_Price" : null,
"quantity" : 40,
}
{
"_id" : 2,
"item_name" : "Banana",
"total_Price" : 1000,
"quantity" : 72,
}
{
"_id" : 3,
"item_name" : "Cherry",
"total_Price" : 215,
"quantity" : 25,
}
{
"_id" : 4,
"item_name" : "Apple",
"total_Price" : null,
"quantity" : 25,
}
{
"_id" : 5,
"item_name" : "Banana",
"total_Price" : 400,
"quantity" : 35,
}
{
"_id" : 6,
"item_name" : "Banana",
"total_Price" : 510,
"quantity" : 100,
}
{
"_id" : 7,
"item_name" : "Cherry",
"total_Price" : 500,
"quantity" : 41,
}
{
"_id" : 8,
"item_name" : "Rasbhari",
"total_Price" : 80,
"quantity" : "Ten",
}
{
"_id" : 9,
"item_name" : "Banana",
"total_Price" : 205,
"quantity" : 10,
}
{
"_id" : 10,
"item_name" : "Apple",
"total_Price" : 95,
"quantity" : null,
}
}
示例 1:使用 $mod 运算符查找余数 在此示例中,我们将使用 $mod 运算符通过将 "total_Price" 字段的值除以 "quantity" 字段来查找余数。 输出 {
"_id" : 2,
"item_name" : "Banana",
"total_Price" : 1000,
"quantity" : 72,
"remainderValue" : 64
}
{
"_id" : 5,
"item_name" : "Banana",
"total_Price" : 400,
"quantity" : 35,
"remainderValue" : 15
}
{
"_id" : 6,
"item_name" : "Banana",
"total_Price" : 510,
"quantity" : 100,
"remainderValue" : 10
}
{
"_id" : 9,
"item_name" : "Banana",
"total_Price" : 205,
"quantity" : 10,
"remainderValue" : 5
}
示例 2:错误的数据类型 $mod 运算符仅支持数值数据类型。如果该值是字符串,则 $mod 运算符将返回错误。 输出 uncaught exception: Error: command failed: {
"ok" : 0,
"errmsg" : "$mod only supports numeric types, not string and double",
"code" : 16611,
"codeName" : "Location16611"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:639:17
assert.commandWorked@src/mongo/shell/assert.js:729:16
DB.prototype._runAggregate@src/mongo/shell/db.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1058:12
@(shell):1:1
示例 3:空值 在此示例中,我们将使用 $mod 运算符通过将 "total_Price" 字段的值除以苹果中的 "quantity" 字段来查找余数。 输出 {
"_id" : 1,
"item_name" : "Apple",
"total_Price" : null,
"quantity" : 40,
"remainderValue" : null
}
{
"_id" : 4,
"item_name" : "Apple",
"total_Price" : null,
"quantity" : 25,
"remainderValue" : null
}
{
"_id" : 10,
"item_name" : "Apple",
"total_Price" : 95,
"quantity" : null,
"remainderValue" : null
}
|
我们请求您订阅我们的新闻通讯以获取最新更新。