Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SDK database Command-aggregate operator-remember operator


May 20, 2021 WeChat Mini Program Development Document


Table of contents


AggregateCommand.addToSet(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. T he aggregation operator. A dd a value to the array and do nothing if it already exists in the array. It can only be used in group stage.

Parameters

value: Expression

The expression

Returns a value

Object

API description

The addToSet syntax is as follows:

db.command.aggregate.addToSet(<表达式>)

An expression is a string that is shaped like $ , specifying a field. If the value of the specified field is an array, the entire array is treated as an element.

The sample code

Suppose the records for the collection passages are as follows:

{ "category": "web", "tags": [ "JavaScript", "CSS" ], "title": "title1" }
{ "category": "System", "tags": [ "C++", "C" ], "title": "title2" }

Non-array fields

The type of category corresponding value for each record is a non-array, using addToSet to count all categories:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    categories: $.addToSet('$category')
  })
  .end()

The results returned are as follows:

{ "_id": null, "categories": [ "System", "web" ] }

Array field

The type of tags corresponding to the value for each record is an array, which is not automatically expanded:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    tagsList: $.addToSet('$tags')
  })
  .end()

The results returned are as follows:

{ "_id": null, "tagsList": [ [ "C++", "C" ], [ "JavaScript", "CSS" ] ] }

AggregateCommand.avg(value: Expression<number>): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns a set of collections that specify the average value of the data for the field.

Parameters

value: Expression<number>

number

Returns a value

Object

API description

The syntax of avg is as follows:

db.command.aggregate.avg(<number>)

The value passed in by avg can be any expression that eventually resolves to a number, in addition to the numeric constant. It ignores non-numeric values.

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

Avg allows you to calculate the average of the score for all records:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: null,
    average: $.avg('$score')
  })
  .end()

The results returned are as follows:

{ "_id": null, "average": 90 }

AggregateCommand.first(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. R eturns the value that corresponds to the first record of the specified field in a set of collections. This action makes sense only if the collection is sorted by some definition.

Parameters

value: Expression

The expression

Returns a value

Object

API description

The syntax for first is as follows:

db.command.aggregate.first(<表达式>)

An expression is a string that is shaped like $ , specifying a field.

First can only be used at the group stage, and it makes sense to work with sort.

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

If you need to get the minimum value of the score in all records, you can sort all records by score and then take out the first of the first record.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1
  })
  .group({
    _id: null,
    min: $.first('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": null, "min": 80 }

AggregateCommand.last(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. R eturns the value of the specified field for the last record in a set of collections. This action makes sense only if the collection is sorted by some definition.

Parameters

value: Expression

The expression

Returns a value

Object

API description

The syntax for last is as follows:

db.command.aggregate.last(<表达式>)

An expression is a string that is shaped like $ , specifying a field.

Last can only be used at the group stage and needs to be matched to make sense.

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

If you need to get the maximum value of the score in all records, you can sort all records by score and then take out the last of the last record.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1
  })
  .group({
    _id: null,
    max: $.last('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": null, "max": 100 }

AggregateCommand.max(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns the maximum value for a set of values.

Parameters

value: Expression

The expression

Returns a value

Object

API description

Max's syntax is as follows:

db.command.aggregate.max(<表达式>)

An expression is a string that is shaped like $ , specifying a field.

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

Max allows you to count the highest scores in different groups, under the following code:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    maxScore: $.max('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": "b", "maxScore": 100 }
{ "_id": "a", "maxScore": 96 }
```.

AggregateCommand.mergeObjects(value: Expression<document>): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Combine multiple documents into a single document.

Parameters

value: Expression<document>

Document expression

Returns a value

Object

API description

Use as follows: When used in group():

mergeObjects(<document>)

When used in other expressions:

mergeObjects([<document1>, <document2>, ...])

The sample code

Use with group().

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 } }

General usage

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 } }

AggregateCommand.min(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns the minimum value of a set of values.

Parameters

value: Expression

The expression

Returns a value

Object

API description

The syntax for min is as follows:

db.command.aggregate.min(<表达式>)

An expression is a string that is shaped like $ , specifying a field.

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

Min allows you to count the lowest scores in different groups, as follows:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    minScore: $.min('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": "b", "minScore": 80 }
{ "_id": "a", "minScore": 84 }

AggregateCommand.push(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. During the group stage, an array of expressions in a set of expressions is returned that specifies that the columns are composed together with the corresponding values.

Parameters

value: any

Returns a value

Object

API description

The push syntax is as follows:

db.command.aggregate.push({
  <字段名1>: <指定字段1>,
  <字段名2>: <指定字段2>,
  ...
})

The sample code

Suppose the records for the collection students are as follows:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

With the push operation, all data is aggregated and placed in a new field for all records in different groups to further structure and semantic data.

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    students: $.push({
      name: '$name',
      score: '$score'
    })
  })
  .end()

The output is as follows:

{ "_id": "b", "students": [{ "name": "stu3", "score": 80 }, { "name": "stu4", "score": 100 }] }
{ "_id": "a", "students": [{ "name": "stu1", "score": 84 }, { "name": "stu2", "score": 96 }] }

AggregateCommand.stdDevPop(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns a set of fields that correspond to the standard deviation of the value.

Parameters

value: Expression

The expression

Returns a value

Object

API description

StdDevPop is used in the following form:

db.command.aggregate.stdDevPop(<表达式>)

The expression is passed in with the specified field, and the data type of the value corresponding to the specified field must be number, otherwise the result will return null.

The sample code

Suppose the records of the collection students are as follows: group a student's grades are 84 and 96, and group b students' scores are 80 and 100, respectively.

{ "group":"a", "score":84 }
{ "group":"a", "score":96 }
{ "group":"b", "score":80 }
{ "group":"b", "score":100 }

You can use stdDevPop to calculate the standard deviation between a and b students' grades, respectively, to compare which group's grades are more stable. The code is as follows:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: '$group',
    stdDev: $.stdDevPop('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": "b", "stdDev": 10 }
{ "_id": "a", "stdDev": 6 }

AggregateCommand.stdDevSamp(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. C alculate the sample standard deviation for the input value. If the input value represents the data population, or does not summarize more data, use db.command.aggregate.stdDevPop between .

Parameters

value: Expression

The expression

Returns a value

Object

API description

StdDevSamp is used in the following form:

db.command.aggregate.stdDevSamp(<表达式>)

The expression is passed in to the specified field, and stdDevSamp automatically ignores non-numeric values. If all the values in the specified field are non-numeral, the result returns null.

The sample code

Suppose the records for the collection students are as follows:

{ "score": 80 }
{ "score": 100 }

The standard sample deviation for the score can be calculated using stdDevSamp. The code is as follows:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: null,
    ageStdDev: $.stdDevSamp('$score')
  })
  .end()

The results of the data returned are as follows:

{ "_id": null, "ageStdDev": 14.142135623730951 }

If you add a new record to the collection students, its score field type is string:

{ "score": "aa" }

When the standard sample deviation is calculated using the code above, stdDevSamp automatically ignores records of a type other than number, and the return result remains the same.


AggregateCommand.sum(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Calculates and returns the sum of all the values in a set of fields.

Parameters

value: Expression

The expression

Returns a value

Object

API description

Sum is used in the following form:

db.command.aggregate.sum(<表达式>)

Expressions can pass in a specified field, or they can pass in a list of specified fields. s um automatically ignores non-numeric values. I f all values under the field are non-digits, the result returns 0. If a numeric constant is passed in, the value of the field is given as all records, added at the time of aggregation, and the final value is the number of input records multiplied by the constant.

The sample code

Suppose the record of goods, which represents a collection of items, is as follows: price represents sales of goods, and cost represents the cost of goods

{ "cost": -10, "price": 100 }
{ "cost": -15, "price": 1 }
{ "cost": -10, "price": 10 }

Individual fields

Sum allows you to calculate the sum of sales of all goods under the following code:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalPrice: $.sum('$price')
  })
  .end()

The result of the data returned is as follows: Sales are 111

{ "_id": null, "totalPrice": 111 }

The list of fields

If you need to calculate the total profit for all goods, you need to add the cost and price of each record to get the profit for the corresponding item for this record. Finally, the total profit of all goods is calculated.

With sum, the code is as follows:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalProfit: $.sum(
      $.sum(['$price', '$cost'])
    )
  })
  .end()

The data result returned is as follows: Total profit is 76

{ "_id": null, "totalProfit": 76 }