$indexOfCP - Amazon DocumentDB

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

$indexOfCP

Amazon DocumentDB 中的$indexOfCP运算符用于以码点 (CP) 形式查找字符串表达式中指定子字符串首次出现的索引。这在解析和提取字符串字段中的内容时非常有用。

参数

  • string expression: 要搜索的字符串。

  • substring: 要搜索的子字符串。

  • [<start>]:(可选)开始搜索的位置(从零开始的索引)。默认值为 0。

示例(MongoDB 外壳)

在此示例中,我们使用$indexOfCP运算符在每个文档的 Desk 字段中查找首次出现的连字符的索引。

创建示例文档

db.people.insertMany([ { "_id":1, "name":"John Doe", "Manager":"Jane Doe", "Role":"Developer", "Desk": "Düsseldorf-BVV-021"}, { "_id":2, "name":"John Stiles", "Manager":"Jane Doe", "Role":"Manager", "Desk": "Munich-HGG-32a"}, { "_id":3, "name":"Richard Roe", "Manager":"Jorge Souza", "Role":"Product", "Desk": "Cologne-ayu-892.50"}, { "_id":4, "name":"Mary Major", "Manager":"Jane Doe", "Role":"Solution Architect", "Desk": "Dortmund-Hop-78"} ])

查询示例

db.people.aggregate([ { $project: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } } ])

输出

{ "_id" : 1, "stateLocation" : 10 } { "_id" : 2, "stateLocation" : 6 } { "_id" : 3, "stateLocation" : 7 } { "_id" : 4, "stateLocation" : 8 }

代码示例

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

Node.js
const { MongoClient } = require('mongodb'); async function main() { 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: { stateLocation: { $indexOfCP: [ "$Desk", "-"] } } } ]).toArray(); console.log(result); await client.close(); } main();
Python
from pymongo import MongoClient 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': { 'stateLocation': { '$indexOfCP': [ '$Desk', '-' ] } } } ])) print(result) client.close()