$range - Amazon DocumentDB

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

$range

Amazon DocumentDB の$range集計演算子は、指定された範囲内の連続した数値の配列を作成するために使用されます。この演算子は、以下の例に示すように、レースの補助ステーションのマイルマーカーなど、一連の数値を生成するのに特に便利です。

パラメータ

  • start: 範囲の開始値。

  • end: 範囲の終了値。

  • step: (オプション) 範囲の生成時に使用するステップ値。指定しない場合、デフォルトのステップ値は 1 です。

例 (MongoDB シェル)

この例では、 $range演算子を使用して、自転車レースのウォーターステーションのマイルマーカーを生成します。

サンプルドキュメントを作成する

db.races.insertMany([ { _id: 0, race: "STP", distance: 206 }, { _id: 1, race: "RSVP", distance: 160 }, { _id: 2, race: "Chilly Hilly", distance: 33 }, { _id: 3, race: "Flying Wheels", distance: 100 } ]);

クエリの例

db.races.aggregate([ { $project: { race: 1, "waterStations": { $range: [20, "$distance", 20] } } } ]);

出力

[ { _id: 0, race: 'STP', waterStations: [ 20, 40, 60, 80, 100, 120, 140, 160, 180, 200 ] }, { _id: 1, race: 'RSVP', waterStations: [ 20, 40, 60, 80, 100, 120, 140 ] }, { _id: 2, race: 'Chilly Hilly', waterStations: [ 20 ] }, { _id: 3, race: 'Flying Wheels', waterStations: [ 20, 40, 60, 80 ] } ]

コードの例

$range コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('races'); const pipeline = [ { $project: { race: 1, waterStations: { $range: [20, "$distance", 20] } } } ]; const results = await collection.aggregate(pipeline).toArray(); console.dir(results, { depth: null }); } finally { await client.close(); } } example().catch(console.error);
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') try: db = client.test collection = db.races pipeline = [ { "$project": { "race": 1, "waterStations": { "$range": [20, "$distance", 20] } } } ] results = collection.aggregate(pipeline) for doc in results: print(doc) except Exception as e: print(f"An error occurred: {e}") finally: client.close() example()