

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1mod
<a name="mod-query"></a>

`$mod`查询运算符选择字段值除以除数具有指定余数的文档。这对于根据模算术条件筛选文档很有用。

**参数**
+ `divisor`: 要除以的数字。
+ `remainder`：预期的剩余值。

## 示例（MongoDB 外壳）
<a name="mod-query-examples"></a>

以下示例演示如何使用`$mod`运算符查找数量为奇数的所有订单。

**创建示例文档**

```
db.orders.insertMany([
  { _id: 1, item: "Widget", quantity: 15 },
  { _id: 2, item: "Gadget", quantity: 20 },
  { _id: 3, item: "Tool", quantity: 7 },
  { _id: 4, item: "Device", quantity: 12 },
  { _id: 5, item: "Part", quantity: 9 }
]);
```

**查询示例**

```
db.orders.find({ quantity: { $mod: [2, 1] } });
```

**输出**

```
{ "_id" : 1, "item" : "Widget", "quantity" : 15 }
{ "_id" : 3, "item" : "Tool", "quantity" : 7 }
{ "_id" : 5, "item" : "Part", "quantity" : 9 }
```

此查询返回的文档中，数量除以 2 的余数为 1，实际上选择了所有奇数。

## 代码示例
<a name="mod-query-code"></a>

要查看使用`$mod`查询运算符的代码示例，请选择要使用的语言对应的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.find({ quantity: { $mod: [2, 1] } }).toArray();

  console.log(JSON.stringify(result, null, 2));
  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.find({'quantity': {'$mod': [2, 1]}}))

    print(result)
    client.close()

example()
```

------