$arrayToObject - Amazon DocumentDB

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

$arrayToObject

Amazon DocumentDB 中的$arrayToObject運算子是$objectToArray運算子的反向。它需要一系列鍵值對文件,並將其轉換為單一文件。當您需要將一組鍵/值對轉換回物件或文件結構時,這特別有用。

參數

  • array expression:解析為陣列的表達式。陣列元素必須是具有兩個欄位的文件: k(索引鍵) 和 v(值)。

範例 (MongoDB Shell)

以下範例示範如何使用 $arrayToObject將鍵值對陣列轉換回文件。

建立範例文件

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" } } }, { $project: { name: 1, inventory: { $arrayToObject: "$videos" } } } ]);

輸出

{ "_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 } }

在此範例中,運算$objectToArray子用於將inventory物件轉換為金鑰/值對的陣列。然後,運算$arrayToObject子會用來將陣列轉換回文件,還原原始物件結構。

程式碼範例

若要檢視使用 $arrayToObject命令的程式碼範例,請選擇您要使用的語言標籤:

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('videos'); const result = await collection.aggregate([ { $project: { name: 1, videos: { $objectToArray: '$inventory' } } }, { $project: { name: 1, inventory: { $arrayToObject: '$videos' } } } ]).toArray(); console.log(result); await 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['videos'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'videos': { '$objectToArray': '$inventory' } } }, { '$project': { 'name': 1, 'inventory': { '$arrayToObject': '$videos' } } } ])) print(result) client.close() example()