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