# Collection.orderBy / Query.orderBy

Specifies the sorting criteria of query.

The method signature is shown as below:

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

The method accepts a required string parameter fieldName to define the field to be sorted, and a string parameter order to define the sorting order. The available values for order include asc or desc.

You can also sort multiple fields by calling orderBy several times in the order of calling orderBy.

Sample code: Sort a single field

Get to-dos in ascending order of progress

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos').orderBy('progress', 'asc').get()
}

Sample code: Sort multiple fields

Get to-dos in descending order of progress (starting from the largest value of progress) and then in order of ascending description (in alphabetical order):

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos')
    .orderBy('progress', 'desc')
    .orderBy('description', 'asc')
    .get()
}
点击咨询小助手