$mod

On this page本页内容

$mod

Select documents where the value of a field divided by a divisor has the specified remainder (i.e. perform a modulo operation to select documents). 选择字段值除以除数后具有指定余数的文档(即执行模运算以选择文档)。To specify a $mod expression, use the following syntax:要指定$mod表达式,请使用以下语法:

{ field: { $mod: [ divisor, remainder ] } }

The $mod operator errors when passed an array with fewer or more than two elements. $mod运算符在传递包含少于或多于两个元素的数组时出错。See Not Enough Elements Error and Too Many Elements Error for details.有关详细信息,请参阅元素不足错误元素过多错误。

Examples示例

Use $mod to Select Documents使用$mod选择文档

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

{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

Then, the following query selects those documents in the inventory collection where value of the qty field modulo 4 equals 0:然后,以下查询选择inventory集合中qty字段模4的值等于0的那些单据:

db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )

The query returns the following documents:查询将返回以下文档:

{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

Not Enough Elements Error错误元素不足

The $mod operator errors when passed an array with fewer than two elements.$mod运算符在传递少于两个元素的数组时出错。

Array with Single Element单元素数组

The following operation incorrectly passes the $mod operator an array that contains a single element:以下操作错误地将包含单个元素的数组传递给$mod运算符:

db.inventory.find( { qty: { $mod: [ 4 ] } } )

The statement results in the following error:该语句导致以下错误:

error: {
     "$err" : "bad query: BadValue malformed mod, not enough elements",
     "code" : 16810
}

Empty Array空数组

The following operation incorrectly passes the $mod operator an empty array:以下操作错误地将空数组传递给$mod运算符:

db.inventory.find( { qty: { $mod: [ ] } } )

The statement results in the following error:该语句导致以下错误:

error: {
     "$err" : "bad query: BadValue malformed mod, not enough elements",
     "code" : 16810
}

Too Many Elements Error错误元素太多

The $mod operator errors when passed an array with more than two elements.$mod运算符在传递包含两个以上元素的数组时出错。

For example, the following operation attempts to use the $mod operator with an array that contains four elements:例如,以下操作尝试将$mod运算符用于包含四个元素的数组:

error: {
     "$err" : "bad query: BadValue malformed mod, too many elements",
     "code" : 16810
}