WeChat Miniprogram Cloud Database Collection/Query .orderBy Usage

Translation Notice
This article was machine-translated using DeepSeek-R1.

  • Original Version: Authored in Chinese by myself
  • Accuracy Advisory: Potential discrepancies may exist between translations
  • Precedence: The Chinese text shall prevail in case of ambiguity
  • Feedback: Technical suggestions regarding translation quality are welcomed

Collection.orderBy / Query.orderBy

Specify query sorting conditions

Method signature:

1
function orderBy(fieldName: string, order: string): Collection | Query

The method takes a required string parameter fieldName to define the field to sort, and a string parameter order to define the sort direction. order can only be asc or desc.

To sort nested fields, use “dot notation” to connect nested fields. For example, style.color represents the nested field color within the style field.

Supports sorting by multiple fields through multiple orderBy calls. The sort order of multiple fields will follow the sequence of orderBy calls.

Example code:

  • Sort by single field: Retrieve todos sorted by progress in ascending order
1
2
3
4
5
const db = wx.cloud.database()
db.collection('todos').orderBy('progress', 'asc')
  .get()
  .then(console.log)
  .catch(console.error)
  • Sort by multiple fields:
    Retrieve todos first sorted by progress descending (higher progress first), then by description ascending (earlier alphabetical order first):
1
2
3
4
5
6
7
const db = wx.cloud.database()
db.collection('todos')
  .orderBy('progress', 'desc')
  .orderBy('description', 'asc')
  .get()
  .then(console.log)
  .catch(console.error)

Source: WeChat Official Documentation · Mini Program -> Cloud Development -> Database -> Collection.orderBy / Query.orderBy

Built with Hugo
Theme Stack designed by Jimmy