cursor.sort()

Definition

  • cursor.sort(sort)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Specifies the order in which the query returns matching documents.You must apply sort() to the cursor beforeretrieving any documents from the database.

The sort() method has the following parameter:

ParameterTypeDescriptionsortdocumentA document that defines the sort order of the result set.

The sort parameter contains field and value pairs, in thefollowing form:

  1. { field: value }

The sort document can specify ascending or descending sort onexisting fields or sort on computed metadata.

Behaviors

Result Ordering

Unless you specify the sort() method or use the$near operator, MongoDB does not guarantee the order ofquery results.

Ascending/Descending Sort

Specify in the sort parameter the field or fields to sort by and avalue of 1 or -1 to specify an ascending or descending sortrespectively.

The following sample document specifies a descending sort by theage field and then an ascending sort by the posts field:

  1. { age : -1, posts: 1 }

When comparing values of different BSON types,MongoDB uses the following comparison order, from lowest to highest:

  • MinKey (internal type)
  • Null
  • Numbers (ints, longs, doubles, decimals)
  • Symbol, String
  • Object
  • Array
  • BinData
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Regular Expression
  • MaxKey (internal type)For details on the comparison/sort order for specific types, seeComparison/Sort Order.

Metadata Sort

Specify in the sort parameter a new field name for thecomputed metadata and specify the $meta expression as itsvalue.

The following sample document specifies a descending sort by the"textScore" metadata:

  1. { score: { $meta: "textScore" } }

The specified metadata determines the sort order. For example, the"textScore" metadata sorts in descending order. See$meta for details.

Restrictions

When unable to obtain the sort order from an index, MongoDB will sortthe results in memory, which requires that the result set being sortedis less than 32 megabytes.

When the sort operation consumes more than 32 megabytes, MongoDBreturns an error. To avoid this error, either create an indexsupporting the sort operation (see Sort and Index Use) or usesort() in conjunction with limit()(see Limit Results).

Sort and Index Use

The sort can sometimes be satisfied by scanning an index in order. Ifthe query plan uses an index to provide the requested sort order,MongoDB does not perform an in-memory sorting of the result set. Formore information, see Use Indexes to Sort Query Results.

Limit Results

You can use sort() in conjunction withlimit() to return the first (in terms of the sortorder) k documents, where k is the specified limit.

If MongoDB cannot obtain the sort order via an index scan, then MongoDBuses a top-k sort algorithm. This algorithm buffers the first kresults (or last, depending on the sort order) seen so far by theunderlying index or collection access. If at any point the memoryfootprint of these k results exceeds 32 megabytes, the query willfail.

Interaction with Projection

When a set of results are both sorted and projected, the MongoDB query enginewill always apply the sorting first.

Examples

A collection orders contain the following documents:

  1. { _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
  2. { _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
  3. { _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }
  4. { _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
  5. { _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
  6. { _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }

The following query, which returns all documents from the orderscollection, does not specify a sort order:

  1. db.orders.find()

The query returns the documents in indeterminate order:

  1. { "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
  2. { "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
  3. { "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
  4. { "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
  5. { "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
  6. { "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }

The following query specifies a sort on the amount field indescending order.

  1. db.orders.find().sort( { amount: -1 } )

The query returns the following documents, in descending order ofamount:

  1. { "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
  2. { "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
  3. { "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
  4. { "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
  5. { "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
  6. { "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }

The following query specifies the sort order using the fields from anembedded document item. The query sorts first by the category fieldin ascending order, and then within each category, by the typefield in ascending order.

  1. db.orders.find().sort( { "item.category": 1, "item.type": 1 } )

The query returns the following documents, ordered first by thecategory field, and within each category, by the type field:

  1. { "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }
  2. { "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
  3. { "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
  4. { "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
  5. { "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
  6. { "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }

Return in Natural Order

The $natural parameter returns items according to theirnatural order within the database. This ordering is an internalimplementation feature, and you should not rely on any particular structurewithin it.

Note

You cannot specify a $natural sort on a view.

Index Use

Queries that include a sort by $natural order do notuse indexes to fulfill the query predicate with the followingexception: If the query predicate is an equality condition on the_id field { _id: <value> }, then the query with the sort by$natural order can use the _id index.

See also

$natural