db.command.aggregate.arrayToObject
1. Operator Description
Function: Converts an array to an object.
Declaration:
Two forms
- Pass in a two-dimensional array where each sub-array must have a length of 2, with the first element as the field name and the second as the field value.
db.command.aggregate.arrayToObject([ [key1, value1], [key2, value2], ... ])
- Pass in an array of objects where each object must contain the fields
k
andv
, specifying the field name and field value respectively.
db.command.aggregate.arrayToObject([ { "k": key1, "v": value1 }, { "k": key2, "v": value2 }, ... ])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array> Array Or Object | Required | as described in the declaration |
3. Sample Code
Suppose the collection shops
contains the following records:
{ "_id": 1, "sales": [ ["max", 100], ["min", 50] ] }
{ "_id": 2, "sales": [ ["max", 70], ["min", 60] ] }
{ "_id": 3, "sales": [ { "k": "max", "v": 50 }, { "k": "min", "v": 30 } ] }
Calculate the score of the first exam and the score of the last exam for each:
// 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
exports.main = async (event, context) => {
const res = await db
.collection('shops')
.aggregate()
.project({
sales: $.arrayToObject('$sales')
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "sales": { "max": 100, "min": 50 } }
{ "_id": 2, "sales": { "max": 70, "min": 60 } }
{ "_id": 3, "sales": { "max": 50, "min": 30 } }