本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$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命令的代码示例,请选择要使用的语言的选项卡: