$mod (aggregation)
定義
構文
The $mod
expression has the following syntax:
{ $mod: [ <expression1>, <expression2> ] }
The first argument is the dividend, and the second argument is the divisor. That is, the first argument is divided by the second argument.
動作
引数は、数値に変換される限り、どのような有効な式でもかまいません。式の詳細については、「式演算子」を参照してください。
Starting in version 7.2, the output data type of the $mod
operator is
the larger of the two input data types.
注意
Prior to version 7.2, the value and field type of inputs determine
the $mod
output type if:
The divisor is type
double
but has an integer value.The dividend is type
int
orlong
.
In this case, MongoDB converts the divisor to the dividend data
type before it performs the $mod
operation. The output data type
is the dividend data type.
マイナス配当
配当がマイナスの場合、余りもマイナスになります。 この動作の詳細については、 公式のJavaScriptドキュメント を参照してください 。
例については、「 負の配当」を参照してください。
例
以下のドキュメントを持つconferencePlanning
コレクションを考えてみましょう。
db.conferencePlanning.insertMany( [ { "_id" : 1, "city" : "New York", "hours" : 80, "tasks" : 7 }, { "_id" : 2, "city" : "Singapore", "hours" : 40, "tasks" : 4 } ] )
The following aggregation uses the $mod
expression to
return the remainder of the hours
field divided by the tasks
field:
db.conferencePlanning.aggregate( [ { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } } ] )
この操作は次の結果を返します。
[ { '_id' : 1, 'remainder' : 3 }, { '_id' : 2, 'remainder' : 0 } ]
マイナス配当
Consider a modExample
collection that contains the following
document:
db.modExample.insertOne( [ { "_id" : 1, "dividend": -13, "divisor": 9 } ] )
This aggregation uses the $mod
expression to return the remainder of
dividend
divided by the divisor
field:
db.modExample.aggregate( [ { $project: { remainder: { $mod: [ "$dividend", "$divisor" ] } } } ] )
この操作は次の結果を返します。
[ { '_id' : 1, 'remainder' : -4 } ]