Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$objectToArray
Amazon DocumentDB 中的$objectToArray聚合运算符将对象(或文档)转换为数组。运算符的输入是一个文档,输出由输入文档中每个字段值对的数组元素组成。当您需要将文档的各个字段作为数组处理时,例如要查找具有特定字段最大值或最小值的文档时,此运算符很有用。
参数
示例(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()