$objectToArray - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$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 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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()