$indexOfCP - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$indexOfCP

Amazon DocumentDB 中的$indexOfCP運算子用於尋找字串表達式中第一次出現指定子字串的索引,以程式碼點 (CP) 為單位。這在剖析和擷取字串欄位的內容時非常有用。

參數

  • string expression:要搜尋的字串。

  • substring:要搜尋的子字串。

  • [<start>]:(選用) 開始搜尋的位置 (以零為基礎的索引)。預設值為 0。

範例 (MongoDB Shell)

在此範例中,我們使用 $indexOfCP運算子在每個文件的桌面欄位中尋找第一個連字號字元的索引。

建立範例文件

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