Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$indexOfBytes
Amazon DocumentDB 中的 $ indexOfBytes 运算符用于根据字符的字节位置查找字符串中子字符串的起始索引。这在处理可能包含多字节字符(例如非拉丁语脚本中的字符)的文本数据时非常有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用在一组$indexOfBytes表示办公桌位置的字符串中查找第一个连字符的索引。
创建示例文档
db.people.insertMany([
{ "_id": 1, "Desk": "Düsseldorf-BVV-021" },
{ "_id": 2, "Desk": "Munich-HGG-32a" },
{ "_id": 3, "Desk": "Cologne-ayu-892.50" },
{ "_id": 4, "Desk": "Dortmund-Hop-78" }
]);
查询示例
db.people.aggregate([
{ $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
]);
输出
{ "_id" : 1, "stateLocation" : 11 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
代码示例
要查看使用该$indexOfBytes命令的代码示例,请选择要使用的语言的选项卡:
- 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 events = db.collection('people');
const result = await db.collection('people').aggregate([
{ $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
]).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(db.people.aggregate([
{ '$project': { 'stateLocation': { '$indexOfBytes': ['$Desk', '-'] } } }
]))
print(result)
client.close()
example()