$objectToArray - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$objectToArray

Amazon DocumentDB $objectToArray 中的彙總運算子會將物件 (或文件) 轉換為陣列。運算子的輸入是文件,而輸出包含輸入文件中每個欄位值對的陣列元素。當您需要使用文件的個別欄位做為陣列時,例如當您想要尋找具有特定欄位最大值或最小值的文件時,此運算子非常有用。

參數

  • expression:要轉換為陣列的文件表達式。

範例 (MongoDB Shell)

下列範例示範如何使用 $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()