$arrayToObject - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$arrayToObject

Amazon DocumentDB 中的$arrayToObject运算符与运算符相反。$objectToArray它接受一组键值对文档并将其转换为单个文档。当你需要将一组键值对转换回对象或文档结构时,这特别有用。

参数

  • array expression: 解析为数组的表达式。数组元素必须是包含两个字段的文档:k(键)和v(值)。

示例(MongoDB 外壳)

下面的示例演示了$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()