$toObjectId - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$toObjectId

버전 4.0의 새로운 기능

Amazon DocumentDB의 $toObjectId 연산자는 ObjectId의 문자열 표현을 실제 ObjectId 데이터 유형으로 변환하는 데 사용됩니다. ObjectIds 데이터 형식이 필요한 작업을 수행할 수 있으므로 ObjectId의 문자열 표현으로 저장된 데이터로 작업할 때 유용할 수 있습니다.

파라미터

  • expression: 유효한 ObjectId를 나타내는 문자열 표현식입니다.

예제(MongoDB 쉘)

다음 예제에서는 $toObjectId 연산자를 사용하여 ObjectId의 문자열 표현을 ObjectId 데이터 형식으로 변환하는 방법을 보여줍니다.

샘플 문서 생성

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

쿼리 예제

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

출력

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

코드 예제

$toObjectId 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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