$toObjectId - Amazon DocumentDB

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

$toObjectId

Baru dari versi 4.0

$toObjectIdOperator di Amazon DocumentDB digunakan untuk mengonversi representasi string dari tipe data aktual ke tipe ObjectId data ObjectId aktual. Hal ini dapat berguna ketika bekerja dengan data yang telah disimpan sebagai representasi string ObjectIds, karena memungkinkan Anda untuk melakukan operasi yang memerlukan tipe ObjectId data.

Parameter

  • expression: Ekspresi string yang mewakili valid ObjectId.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan bagaimana menggunakan $toObjectId operator untuk mengkonversi representasi string dari tipe ObjectId data. ObjectId

Buat dokumen sampel

db.employees.insertMany([ { _id: 1, empId:"64e5f8886218c620cf0e8f8a", name: "Carol Smith", employeeId: "c720a" }, { _id: 2, empId:"64e5f94e6218c620cf0e8f8c", name: "Bill Taylor", employeeId: "c721a" } ]);

Contoh kueri

db.employees.aggregate([ { $project: { "empIdAsObjectId": {$toObjectId: "$empId"}} } ]);

Keluaran

[ { _id: 1, empIdAsObjectId: ObjectId('64e5f8886218c620cf0e8f8a') }, { _id: 2, empIdAsObjectId: ObjectId('64e5f94e6218c620cf0e8f8c') } ]

Contoh kode

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

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 collection = db.collection('employees'); const result = await collection.aggregate([ { $project: { "empIdAsObjectId": {$toObjectId: "$empId"}} } ]).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'] collection = db['employees'] result = list(collection.aggregate([ { "$project": { "empIdAsObjectId": {"$toObjectId": "$empId"}} } ])) print(result) client.close() example()