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

SDK database Command,aggregate operator, array operator


May 20, 2021 WeChat Mini Program Development Document


Table of contents

1. Parameters

2. Returns a value

3. API description

4. The sample code

5. Parameters

6. Returns a value

7. API description

8. The sample code

9. Parameters

10. Returns a value

11. API description

12. The sample code

13. Parameters

14. Returns a value

15. API description

16. The sample code

17. Parameters

18. Returns a value

19. API description

20. The sample code

21. Parameters

22. Returns a value

23. API description

24. The sample code

25. Parameters

26. Returns a value

27. API description

28. The sample code

29. Parameters

30. Returns a value

31. API description

32. The sample code

33. Parameters

34. Returns a value

35. API description

36. The sample code

37. Parameters

38. Returns a value

39. API description

40. The sample code

41. Parameters

42. Returns a value

43. API description

44. The sample code

45. Parameters

46. Returns a value

47. API description

48. The sample code

49. Parameters

50. Returns a value

51. API description

52. The sample code

53. Parameters

54. Returns a value

55. API description

56. The sample code

57. Parameters

58. Returns a value

59. API description

60. The sample code


AggregateCommand.arrayElemAt(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns the element under the specified array.

Parameters

value: Expression[]

[<array>, <index>]

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.arrayElemAt([<array>, <index>])

An expression that can be resolved to a number at will.

An expression that can be resolved to plastic at will. If it is a positive number, arrayElemAt returns the element at the index position, and if it is a negative number, arrayElemAt returns the element at the index position calculated from the end of the array.

The sample code

Suppose the collection exams have the following records:

{ "_id": 1, "scores": [80, 60, 65, 90] }
{ "_id": 2, "scores": [78] }
{ "_id": 3, "scores": [95, 88, 92] }

Ask for scores for each first and last exam:

const $ = db.command.aggregate
db.collection('exams').aggregate()
  .project({
    first: $.arrayElemAt(['$scores', 0]),
    last: $.arrayElemAt(['$scores', -1]),
  })
  .end()

The results are as follows:

{ "_id": 1, "first": 80, "last": 90 }
{ "_id": 2, "first": 78, "last": 78 }
{ "_id": 3, "first": 95, "last": 92 }

AggregateCommand.arrayToObject(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Convert an array to an object.

Parameters

value: any

Returns a value

Object

API description

There are two types of syntax:

The first is an incoming two-dimensional array, the second-dimensional array must be 2 in length, with the first value as the field name and the second as the field value

db.command.aggregate.arrayToObject([
  [<key1>, <value1>],
  [<key2>, <value2>],
  ...
])

The second is an array of objects that must contain fields k and v, specifying the field name and field value, respectively

db.command.aggregate.arrayToObject([
  { "k": <key1>, "v": <value1> },
  { "k": <key2>, "v": <value2> },
  ...
])

The arguments passed in to arrayToObject can be resolved to one of these two notations.

The sample code

Suppose the collection shops have 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 } ] }

Ask for scores for each first and last exam:

const $ = db.command.aggregate
db.collection('shops').aggregate()
  .project({
    sales: $.arrayToObject('$sales'),
  })
  .end()

The results are as follows:

{ "_id": 1, "sales": { "max": 100, "min": 50 } }
{ "_id": 2, "sales": { "max": 70, "min": 60 } }
{ "_id": 3, "sales": { "max": 50, "min": 30 } }

AggregateCommand.concatArrays(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Stitch multiple arrays into one array.

Parameters

value: Expression[]

[ <array1>, <array2>, ... ]

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.arrayToObject([ <array1>, <array2>, ... ])

Arguments can be expressions that resolve arbitrarily into arrays.

The sample code

Suppose the collection items have the following records:

{ "_id": 1, "fruits": [ "apple" ], "vegetables": [ "carrot" ] }
{ "_id": 2, "fruits": [ "orange", "lemon" ], "vegetables": [ "cabbage" ] }
{ "_id": 3, "fruits": [ "strawberry" ], "vegetables": [ "spinach" ] }
const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    list: $.concatArrays(['$fruits', '$vegetables']),
  })
  .end()

The results are as follows:

{ "_id": 1, "list": [ "apple", "carrot" ] }
{ "_id": 2, "list": [ "orange", "lemon", "cabbage" ] }
{ "_id": 3, "list": [ "strawberry", "spinach" ] }

AggregateCommand.filter(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns a subset of arrays that meet the criteria based on a given condition.

Parameters

value: any

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.filter({
  input: <array>,
  as: <string>,
  cond: <expression>
})
Field Description
input An expression that can be resolved to an array
as Optional variable that represents individual elements of the array, which defaults to this
cond An expression that can be resolved to Boolean values to determine whether individual elements meet the as and the names of each element are determined by the as parameter (parameter names need $$ $$this

Arguments can be expressions that resolve arbitrarily into arrays.

The sample code

Suppose the collection fruits have the following records:

{
  "_id": 1,
  "stock": [
    { "name": "apple", "price": 10 },
    { "name": "orange", "price": 20 }
  ],
}
{
  "_id": 2,
  "stock": [
    { "name": "lemon", "price": 15 },
  ],
}
const _ = db.command
const $ = db.command.aggregate
db.collection('fruits').aggregate()
  .project({
    stock: $.filter({
      input: '$stock',
      as: 'item',
      cond: $.gte(['$$item.price', 15])
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "stock": [ { "name": "orange", "price": 20} ] }
{ "_id": 2, "stock": [ { "name": "lemon", "price": 15 } ] }

AggregateCommand.in(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Given a value and an array, if the value is in the array, true is returned, otherwise false is returned.

Parameters

value: Expression[]

[<value>, <array>]

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.in([<value>, <array>])

It can be any expression.

An expression that can be resolved arbitrarily into an array.

The sample code

Suppose the collection shops have the following records:

{ "_id": 1, "topsellers": ["bread", "ice cream", "butter"] }
{ "_id": 2, "topsellers": ["ice cream", "cheese", "yagurt"] }
{ "_id": 3, "topsellers": ["croissant", "cucumber", "coconut"] }

The item that marks the highest selling item contains a record of ice cream.

const $ = db.command.aggregate
db.collection('price').aggregate()
  .project({
    included: $.in(['ice cream', '$topsellers'])
  })
  .end()

The results are as follows:

{ "_id": 1, "included": true }
{ "_id": 2, "included": true }
{ "_id": 3, "included": false }

AggregateCommand.indexOfArray(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Find the lower sign of the first element equal to a given value in the array and return -1 if not found.

Parameters

value: Expression[]

[ <array expression>, <search expression>, <start>, <end> ]

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.indexOfArray([ <array expression>, <search expression>, <start>, <end> ])
Field Type Description
<array> string An expression that resolves to an array, and if it resolves to null, indexOfArray null
<search> string A condition matching expression applied to each element of the data
<start> integer Optional to specify the start of the search, which must be a non-negative integer
<end> integer Optional, to specify the end of the search underrout, must be a non-negative integer, specified <end> when the designation of the <start> <end> <start>

Arguments can be expressions that resolve arbitrarily into arrays.

The sample code

Suppose the collection stats has the following records:

{
  "_id": 1,
  "sales": [ 1, 6, 2, 2, 5 ]
}
{
  "_id": 2,
  "sales": [ 4, 2, 1, 5, 2 ]
}
{
  "_id": 3,
  "sales": [ 2, 5, 3, 3, 1 ]
}
const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    index: $.indexOfArray(['$sales', 2, 2])
  })
  .end()

The results are as follows:

{ "_id": 1, "index": 2 }
{ "_id": 2, "index": 4 }
{ "_id": 3, "index": -1 }

AggregateCommand.isArray(value: Expression): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Determines whether a given expression is an array and returns a Boolean value.

Parameters

value: Expression

The expression

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.isArray(<expression>)

Arguments can be arbitrary expressions.

The sample code

Suppose the collection stats has the following records:

{
  "_id": 1,
  "base": 10,
  "sales": [ 1, 6, 2, 2, 5 ]
}
{
  "_id": 2,
  "base": 1,
  "sales": 100
}

Calculate the total sales volume, if sales is a number, then ask sales s base, and if sales is an array, the sum of array elements and the product of base.

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    sum: $.cond({
      if: $.isArray('$sales'),
      then: $.multiply([$.sum(['$sales']), '$base']),
      else: $.multiply(['$sales', '$base']),
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "index": 160 }
{ "_id": 2, "index": 100 }

AggregateCommand.map(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Similar to the map method on JavaScript Array, each element of a given array is converted to a new array by a given conversion method.

Parameters

value: any

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.map({
  input: <expression>,
  as: <string>,
  in: <expression>
})
Field Description
input An expression that can be resolved to an array
as Optional variable that represents individual elements of the array, which defaults to this
in An expression that can be applied to individual elements of a given array whose as parameter (the parameter name $$ such as $$this

The sample code

Suppose the collection stats has the following records:

{
  "_id": 1,
  "sales": [ 1.32, 6.93, 2.48, 2.82, 5.74 ]
}
{
  "_id": 2,
  "sales": [ 2.97, 7.13, 1.58, 6.37, 3.69 ]
}

Truncated the numbers into shapes, and then reconstructed

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    truncated: $.map({
      input: '$sales',
      as: 'num',
      in: $.trunc('$$num'),
    })
  })
  .project({
    total: $.sum('$truncated')
  })
  .end()

The results are as follows:

{ "_id": 1, "index": 16 }
{ "_id": 2, "index": 19 }

AggregateCommand.objectToArray(value: Expression<object>): Object

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&gt; , v: &lt; v alue&gt; }。

Parameters

value: Expression<object>

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.objectToArray(<object>)

The sample code

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

AggregateCommand.range(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. R eturns a set of generated sequence numbers. Given a start value, an end value, a non-zero step, the range returns a sequence that grows gradually from the start value to a given step, but does not include the end value.

Parameters

value: Expression[]

[<start>, <end>, <non-zero step>]

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.range([<start>, <end>, <non-zero step>])
Field Description
start Start value, an expression that can be resolved to shaping
end End value, an expression that can be resolved to shaping
non-zero step Optional, Step, an expression that resolves to non-zero shaping, defaulting to 1

The sample code

Suppose the collection stats has the following records:

{ "_id": 1, "max": 52 }
{ "_id": 2, "max": 38 }
const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    points: $.range([0, '$max', 10])
  })
  .end()

The results are as follows:

{ "_id": 1, "points": [0, 10, 20, 30, 40, 50] }
{ "_id": 2, "points": [0, 10, 20] }

AggregateCommand.reduce(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. The JavaScript-like reduce method applies an expression to each element of the array and then groups them into one element.

Parameters

value: any

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.reduce({
  input: <array>
  initialValue: <expression>,
  in: <expression>
})
Field Description
input Enter an array, which can be an expression that resolves arbitrarily to an array
initialValue The initial value
in The expression used to act on each element has in in in, value a variable that represents the cumulative this a variable that represents the current array element

The sample code

Easy string stitching

Suppose the collection player has the following record:

{ "_id": 1, "fullname": [ "Stephen", "Curry" ] }
{ "_id": 2, "fullname": [ "Klay", "Thompsom" ] }

Get the full name of each player and add the Player: prefix:

const $ = db.command.aggregate
db.collection('player').aggregate()
  .project({
    info: $.reduce({
      input: '$fullname',
      initialValue: 'Player:',
      in: $.concat(['$$value', ' ', '$$this']),
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "info": "Player: Stephen Curry" }
{ "_id": 2, "info": "Player: Klay Thompson" }

Get the full name of each player without prefix:

const $ = db.command.aggregate
db.collection('player').aggregate()
  .project({
    name: $.reduce({
      input: '$fullname',
      initialValue: '',
      in: $.concat([
        '$$value',
        $.cond({
          if: $.eq(['$$value', '']),
          then: '',
          else: ' ',
        }),
        '$$this',
      ]),
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "name": "Stephen Curry" }
{ "_id": 2, "name": "Klay Thompson" }

AggregateCommand.reverseArray(value: Expression<any[]>): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns the inverted form of a given array.

Parameters

value: Expression<any[]>

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.reverseArray(<array>)

Arguments can be resolved arbitrarily to array expressions.

The sample code

Suppose the collection stats has the following records:

{
  "_id": 1,
  "sales": [ 1, 2, 3, 4, 5 ]
}

Take sales in reverse order:

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    reversed: $.reverseArray('$sales'),
  })
  .end()

The results are as follows:

{ "_id": 1, "reversed": [5, 4, 3, 2, 1] }

AggregateCommand.size(value: Expression<any[]>): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. Returns the length of the array.

Parameters

value: Expression<any[]>

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.size(<array>)

An expression that can be resolved arbitrarily into an array.

The sample code

Suppose the collection shops have the following records:

{ "_id": 1, "staff": [ "John", "Middleton", "George" ] }
{ "_id": 2, "staff": [ "Steph", "Jack" ] }

Calculate the number of employees per store:

const $ = db.command.aggregate
db.collection('staff').aggregate()
  .project({
    totalStaff: $.size('$staff')
  })
  .end()

The results are as follows:

{ "_id": 1, "totalStaff": 3 }
{ "_id": 2, "totalStaff": 2 }

AggregateCommand.slice(value: Expression[]): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. A slice method similar to JavaScritp. Returns a specified subset of a given array.

Parameters

value: Expression[]

[<array>, <n>]

Returns a value

Object

API description

There are two types of syntax:

Returns n elements from the beginning or end:

db.command.aggregate.slice([<array>, <n>])

Returns n elements that count as beginning, back, or forward from the specified location:

db.command.aggregate.slice([<array>, <position>, <n>])

An expression that can be resolved arbitrarily into an array.

It can be an expression that resolves arbitrarily to a shaping. I f it is a positive number, start with the first element of the array, and if the number is longer than the array, slice returns an empty array. In the case of a negative number, the penultimate element of the array starts as an array, and if the absolute value of the array is greater than the length of the array, the starting position is the beginning of the array.

It can be an expression that resolves arbitrarily to a shaping. I f it is available, it must be a positive integer. I f it is a positive number, slice returns the first n elements. If it is a negative number, slice returns the last n elements.

The sample code

Suppose the collection people have the following records:

{ "_id": 1, "hobbies": [ "basketball", "football", "tennis", "badminton" ] }
{ "_id": 2, "hobbies": [ "golf", "handball" ] }
{ "_id": 3, "hobbies": [ "table tennis", "swimming", "rowing" ] }

Return to the first two hobbies:

const $ = db.command.aggregate
db.collection('fruits').aggregate()
  .project({
    hobbies: $.slice(['$hobbies', 2]),
  })
  .end()

The results are as follows:

{ "_id": 1, "hobbies": [ "basketball", "football" ] }
{ "_id": 2, "hobbies": [ "golf", "handball" ] }
{ "_id": 3, "hobbies": [ "table tennis", "swimming" ] }

AggregateCommand.zip(value: any): Object

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregate operator. T he elements of the same serial number in the second-dimensional array of the two-dimensional array are assembled into a new array and then assembled into a new two-dimensional array. I f you can use the s. #34 . a &#34; , &#34; b &#34; , &#34; c &#34; - Converted to the s.1, s.amp;#34; a &#34; ] , [ 2, &#34; b &#34; ] , [ 3, &#34; c &#34; ] ]。

Parameters

value: any

Returns a value

Object

API description

The syntax is as follows:

db.command.aggregate.zip({
  inputs: [<array1>, <array2>, ...],
  useLongestLength: <boolean>,
  defaults: <array>
})

inputs is a two-dimensional array (inputs cannot be a field reference), where the expression of each element (which can be a field reference) can be resolved to an array. I f any of these expressions return null, the null is also returned. If either expression does not point to a legitimate field / resolves to array / resolves to null, an error is returned.

UseLongestLength determines whether the length of the output array is the length of the longest array in the input array. The default is false, which is the length of the shortest array in the input array, which is the length of the elements of the output array.

Defaults is an array that specifies the default values for each element of an array when the length of the input array is different. T o specify this field, you must specify useLongestLength, or an error will be returned. I f useLongestLength is true but defaults are empty or not specified, zip uses null as the default default for array elements. When specifying the default values for each element, the length of the defaults array must be the maximum length of the input array.

The sample code

Suppose the collection stats has the following records:

{ "_id": 1, "zip1": [1, 2], "zip2": [3, 4], "zip3": [5, 6] ] }
{ "_id": 2, "zip1": [1, 2], "zip2": [3], "zip3": [4, 5, 6] ] }
{ "_id": 3, "zip1": [1, 2], "zip2": [3] ] }

Only inputs are passed on

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1', // 字段引用
        '$zip2',
        '$zip3',
      ],
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "zip": [ [1, 3, 5], [2, 4, 6] ] }
{ "_id": 2, "zip": [ [1, 3, 4] ] }
{ "_id": 3, "zip": null }

Set up useLongestLength

If useLongestLength is true:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1', // 字段引用
        '$zip2',
        '$zip3',
      ],
      useLongestLength: true,
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "zip": [ [1, 3, 5], [2, 4, 6] ] }
{ "_id": 2, "zip": [ [1, 3, 4], [2, null, 5], [null, null, 6] ] }
{ "_id": 3, "zip": null }

Set defaults

const $ = db.command.aggregate
db.collection('items').aggregate()
  .project({
    zip: $.zip({
      inputs: [
        '$zip1', // 字段引用
        '$zip2',
        '$zip3',
      ],
      useLongestLength: true,
      defaults: [-300, -200, -100],
    })
  })
  .end()

The results are as follows:

{ "_id": 1, "zip": [ [1, 3, 5], [2, 4, 6] ] }
{ "_id": 2, "zip": [ [1, 3, 4], [2, -200, 5], [-300, -200, 6] ] }
{ "_id": 3, "zip": null }