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

SDK database Aggregate document sorting


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Aggregate.sort(object: Object): Aggregate

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregation phase. Sort the entered documents according to the specified fields.

Parameters

object: Object

Returns a value

Aggregate

API description

The form is as follows:

sort({
    <字段名1>: <排序规则>,
    <字段名2>: <排序规则>,
})

The collation can be the following:

  • 1 for ascending order (small to large);
  • -1 for descending order (from large to small);

Example

Ascending/descending order

Let's say we have a collection of articles that contain the following data:

{ "_id": "1", "author": "stark",  "score": 80, "age": 18 }
{ "_id": "2", "author": "bob",    "score": 60, "age": 18 }
{ "_id": "3", "author": "li",     "score": 55, "age": 19 }
{ "_id": "4", "author": "jimmy",  "score": 60, "age": 22 }
{ "_id": "5", "author": "justan", "score": 95, "age": 33 }
db.collection('articles')
  .aggregate()
  .sort({
      age: -1,
      score: -1
  })
  .end()

The above code performs an aggregate search in the students collection and sorts the results, first in descending order from the age field and then in descending order from the score field.

The output is as follows:

{ "_id": "5", "author": "justan", "score": 95, "age": 33 }
{ "_id": "4", "author": "jimmy",  "score": 60, "age": 22 }
{ "_id": "3", "author": "li",     "score": 55, "age": 19 }
{ "_id": "1", "author": "stark",  "score": 80, "age": 18 }
{ "_id": "2", "author": "bob",    "score": 60, "age": 18 }