May 20, 2021 WeChat Mini Program Development Document
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregate operator. Combine multiple documents into a single document.
Document expression
Use as follows: When used in group():
mergeObjects(<document>)
When used in other expressions:
mergeObjects([<document1>, <document2>, ...])
Suppose the collection sales has 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() and merges documents with the same name:
const $ = db.command.aggregate
db.collection('sales').aggregate()
.group({
_id: '$name',
mergedVolume: $.mergeObjects('$volume')
})
.end()
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 } }
Suppose the collection test has 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(), which combines the foo and bar fields in the document into foobar:
const $ = db.command.aggregate
db.collection('sales').aggregate()
.project({
foobar: $.mergeObjects(['$foo', '$bar'])
})
.end()
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 } }
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregate operator. C onvert an object to an array. M ethod turns each pair of key values of an object into an element of the output array, which is shaped like . k ey> , v: < v alue> }。
The syntax is as follows:
db.command.aggregate.objectToArray(<object>)
Suppose the collection items have the following records:
{ "_id": 1, "attributes": { "color": "red", "price": 150 } }
{ "_id": 2, "attributes": { "color": "blue", "price": 50 } }
{ "_id": 3, "attributes": { "color": "yellow", "price": 10 } }
const $ = db.command.aggregate
db.collection('items').aggregate()
.project({
array: $.objectToArray('$attributes')
})
.end()
The results are 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 }] }