db.command.aggregate.mergeObjects
1. Operator Description
Function: Merges multiple documents into a single document.
Declaration: db.command.aggregate.max(<expression>)
There are two usage forms for expressions as follows:
- When used in
group()
:
mergeObjects(<document>)
- When used in other expressions:
mergeObjects([<document1>, <document2>, ...])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Expression or <Array>Expression | Required | aggregate expression |
3. Sample Code
Used with group()
Suppose the collection sales
contains the following documents:
{ "_id": 1, "year": 2018, "name": "A", "volume": { "2018Q1": 500, "2018Q2": 500 } }
{ "_id": 2, "year": 2017, "name": "A", "volume": { "2017Q1": 400, "2017Q2": 300, "2017Q3": 0, "2017Q4": 0 } }
{ "_id": 3, "year": 2018, "name": "B", "volume": { "2018Q1": 100 } }
{ "_id": 4, "year": 2017, "name": "B", "volume": { "2017Q3": 100, "2017Q4": 250 } }
The following code uses mergeObjects()
to merge documents with the same name
:
// 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('sales')
.aggregate()
.group({
_id: '$name',
mergedVolume: $.mergeObjects('$volume')
})
.end()
console.log(res.data)
}
The output is as follows:
{ "_id": "A", "mergedVolume": { "2017Q1": 400, "2017Q2": 300, "2017Q3": 0, "2017Q4": 0, "2018Q1": 500, "2018Q2": 500 } }
{ "_id": "B", "mergedVolume": { "2017Q3": 100, "2017Q4": 250, "2018Q1": 100 } }
General Usage
Suppose the collection test
contains the following documents:
{ "_id": 1, "foo": { "a": 1 }, "bar": { "b": 2 } }
{ "_id": 2, "foo": { "c": 1 }, "bar": { "d": 2 } }
{ "_id": 3, "foo": { "e": 1 }, "bar": { "f": 2 } }
The following code uses mergeObjects()
to merge the foo
and bar
fields in the documents into foobar
:
// 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('sales')
.aggregate()
.project({
foobar: $.mergeObjects(['$foo', '$bar'])
})
.end()
console.log(res.data)
}
The output is as follows:
{ "_id": 1, "foobar": { "a": 1, "b": 2 } }
{ "_id": 2, "foobar": { "c": 1, "d": 2 } }
{ "_id": 3, "foobar": { "e": 1, "f": 2 } }