SDK數(shù)據(jù)庫 Aggregate·文檔排序

2022-05-12 16:49 更新

Aggregate.sort(object: Object): Aggregate

支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web

聚合階段。根據(jù)指定的字段,對(duì)輸入的文檔進(jìn)行排序。

參數(shù)

object: Object

返回值

Aggregate

API 說明

形式如下:

sort({
    <字段名1>: <排序規(guī)則>,
    <字段名2>: <排序規(guī)則>,
})

<排序規(guī)則>可以是以下取值:

  • 1 代表升序排列(從小到大);
  • -1 代表降序排列(從大到小);

示例

升序/降序排列

假設(shè)我們有集合 articles,其中包含數(shù)據(jù)如下:

{ "_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()

上面的代碼在 students 集合中進(jìn)行聚合搜索,并且將結(jié)果排序,首先根據(jù) age 字段降序排列,然后再根據(jù) score 字段進(jìn)行降序排列。

輸出結(jié)果如下:

{ "_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 }


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)