$objectToArray - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$objectToArray

Amazon DocumentDB の$objectToArray集計演算子は、オブジェクト (またはドキュメント) を配列に変換します。演算子への入力はドキュメントであり、出力は入力ドキュメント内の各フィールドと値のペアの配列要素で構成されます。この演算子は、特定のフィールドの最大値または最小値を持つドキュメントを検索する場合など、ドキュメントの個々のフィールドを配列として操作する必要がある場合に便利です。

パラメータ

  • expression: 配列に変換するドキュメント式。

例 (MongoDB シェル)

次の例は、 $objectToArray演算子を使用して、ビデオレンタルストアチェーンの最大インベントリを持つドキュメントを検索する方法を示しています。

サンプルドキュメントを作成する

db.videos.insertMany([ { "_id": 1, "name": "Live Soft", "inventory": { "Des Moines": 1000, "Ames": 500 } }, { "_id": 2, "name": "Top Pilot", "inventory": { "Mason City": 250, "Des Moines": 1000 } }, { "_id": 3, "name": "Romancing the Rock", "inventory": { "Mason City": 250, "Ames": 500 } }, { "_id": 4, "name": "Bravemind", "inventory": { "Mason City": 250, "Des Moines": 1000, "Ames": 500 } } ]);

クエリの例

db.videos.aggregate([ { $project: { name: 1, videos: { $objectToArray: "$inventory" } } }, { $unwind: "$videos" }, { $group: { _id: "$name", maxInventory: { $max: "$videos.v" } } } ]);

出力

[ { "_id": "Bravemind", "maxInventory": 1000 }, { "_id": "Live Soft", "maxInventory": 1000 }, { "_id": "Romancing the Rock", "maxInventory": 500 }, { "_id": "Top Pilot", "maxInventory": 1000 } ]

コードの例

$objectToArray コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function findMaxInventory() { 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 videos = db.collection('videos'); const result = await videos.aggregate([ { $project: { name: 1, videos: { $objectToArray: "$inventory" } } }, { $unwind: "$videos" }, { $group: { _id: "$name", maxInventory: { $max: "$videos.v" } } } ]).toArray(); console.log(result); client.close(); } findMaxInventory();
Python
from pymongo import MongoClient def find_max_inventory(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] videos = db['videos'] result = list(videos.aggregate([ { '$project': { 'name': 1, 'videos': { '$objectToArray': '$inventory' } } }, { '$unwind': '$videos' }, { '$group': { '_id': '$name', 'maxInventory': { '$max': '$videos.v' } } } ])) print(result) client.close() find_max_inventory()