$indexOfCP - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$indexOfCP

$indexOfCPOperator di Amazon DocumentDB digunakan untuk menemukan indeks, dalam titik kode (CP), dari kemunculan pertama substring tertentu dalam ekspresi string. Ini dapat berguna saat mengurai dan mengekstrak konten dari bidang string.

Parameter

  • string expression: String untuk mencari.

  • substring: Substring untuk mencari.

  • [<start>]: (opsional) Posisi untuk memulai pencarian (indeks berbasis nol). Default-nya adalah 0.

Contoh (MongoDB Shell)

Dalam contoh ini, kami menggunakan $indexOfCP operator untuk menemukan indeks kemunculan pertama karakter tanda hubung - di bidang Desk setiap dokumen.

Buat dokumen sampel

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"} ])

Contoh kueri

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

Keluaran

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

Contoh kode

Untuk melihat contoh kode untuk menggunakan $indexOfCP perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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