$substrBytes - Amazon DocumentDB

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

$substrBytes

Amazon DocumentDB 中的$substrBytes运算符用于根据指定的字节范围从字符串中提取子字符串。当您需要从字符串中提取子字符串并且表示字符串中每个字符所需的字节数很重要时,此运算符很有用。

与之不同$substrCP,它对Unicode码点的数量进行$substrBytes运算,对表示字符串中字符所需的字节数进行运算。这在处理包含非 ASCII 字符的字符串时特别有用,因为这些字符可能需要多个字节才能表示。

*注意:* 自 3.4 版起$substr已被弃用。 $substr现在是的别名$substrBytes

参数

  • string:要从中提取子字符串的输入字符串。

  • startByte:要提取的子字符串的起始字节位置(从零开始)。负值可用于指定从字符串末尾开始的位置。

  • length:要提取的子字符串中的字节数。

示例(MongoDB 外壳)

在此示例中,我们将使用$substrBytes从包含非 ASCII 字符的字符串中提取子字符串。

创建示例文档

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": { $substrBytes: [ "$Desk", 12, 3] } } } ])

输出

{ "_id": 1, "state": "NRW" }, { "_id": 2, "state": "HBB" }, { "_id": 3, "state": "SHH" }, { "_id": 4, "state": "BBB" }

在此示例中,我们使用从字段$substrBytes的第 12 个字节开始提取一个 3 字节的Desk子字符串。这允许我们提取 2 个字符的状态缩写,即使该字符串可能包含非 ASCII 字符。

代码示例

要查看使用该$substrBytes命令的代码示例,请选择要使用的语言的选项卡:

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 people = db.collection('people'); const result = await people.aggregate([ { $project: { "state": { $substrBytes: ["$Desk", 12, 3] } } } ]).toArray(); console.log(result); 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 people = db.people result = list(people.aggregate([ { '$project': { "state": { '$substrBytes': ["$Desk", 12, 3] } } } ])) print(result) client.close() example()