Skip to main content

db.command.aggregate.objectToArray

1. Operator Description

Function: Converts an object to an array. The method transforms each key-value pair of the object into an element in the output array, with each element in the form { k: <key>, v: <value> }.

Declaration: db.command.aggregate.objectToArray(object)

2. Operator Parameters

FieldTypeRequiredDescription
-ObjectYesKey-value pair object

3. Sample Code

Suppose the collection items contains the following records:

{ "_id": 1, "attributes": { "color": "red", "price": 150 } }
{ "_id": 2, "attributes": { "color": "blue", "price": 50 } }
{ "_id": 3, "attributes": { "color": "yellow", "price": 10 } }
// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})

const db = app.database()
const $ = db.command.aggregate
const _ = db.command

exports.main = async (event, context) => {
const res = await db
.collection('items')
.aggregate()
.project({
array: $.objectToArray('$attributes')
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "array": [{ "k": "color", "v": "red" }, { "k": "price", "v": 150 }] }
{ "_id": 2, "array": [{ "k": "color", "v": "blue" }, { "k": "price", "v": 50 }] }
{ "_id": 3, "array": [{ "k": "color", "v": "yellow" }, { "k": "price", "v": 10 }] }