$mod - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$mod

$mod クエリ演算子は、フィールド値を除数で割ったドキュメントに指定された余りがあるドキュメントを選択します。これは、モジュロ算術条件に基づいてドキュメントをフィルタリングする場合に便利です。

パラメータ

  • divisor: 除算する数値。

  • remainder: 予想される余剰値。

例 (MongoDB シェル)

次の例は、 $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 で、すべての奇数を効果的に選択します。

コードの例

$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()