Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$range
Amazon DocumentDB 中的$range聚合运算符用于创建指定范围内连续数字的数组。该运算符对于生成数字序列特别有用,例如比赛中援助站的英里标记,如以下示例所示。
参数
示例(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()