Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$substr
Amazon DocumentDB 中的$substr运算符用于从给定字符串中提取子字符串。当您需要根据字符范围而不是字节范围定义子字符串时,它特别有用。在处理 Unicode 字符串时,这一点尤其重要,因为在这些字符串中,用于表示字符的字节数可能会有所不同。
参数
示例(MongoDB 外壳)
在此示例中,我们将演示如何使用从员工办公桌位置提取州缩写。$substr
创建示例文档
db.people.insertMany([
{ "_id": 1, "Desk": "Düsseldorf-NRW-021" },
{ "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
{ "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
{ "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
查询示例
db.people.aggregate([
{
$project: {
"state": { $substr: ["$Desk", 12, 3] }
}
}
])
输出
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
代码示例
要查看使用该$substr命令的代码示例,请选择要使用的语言的选项卡:
- 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("people");
const result = await collection.aggregate([
{
$project: {
"state": { $substrCP: ["$Desk", 12, 3] }
}
}
]).toArray();
console.log(result);
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["people"]
result = list(collection.aggregate([
{
"$project": {
"state": { "$substrCP": ["$Desk", 12, 3] }
}
}
]))
print(result)
client.close()
example()