$indexOfBytes - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$indexOfBytes

Amazon DocumentDB 中的 $ indexOfBytes 运算符用于根据字符的字节位置查找字符串中子字符串的起始索引。这在处理可能包含多字节字符(例如非拉丁语脚本中的字符)的文本数据时非常有用。

参数

  • string: 要搜索的输入字符串。

  • substring: 要在输入字符串中搜索的子字符串。

  • [<start>]:(可选)搜索的起始位置(从零开始)。如果未指定,则从字符串的开头开始搜索。

示例(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()