KeplerGrid guide

Sort MongoDB documents with sort() and $sort

Use sort() with find() and $sort in an aggregation pipeline. Both take 1 for ascending order and -1 for descending order.

lab.orders.find({ status: "paid" }).sort({ created_at: -1, _id: -1 }).limit(3)

Run the practice data setup in a development database, then paste this query into the same mongosh session. It returns ORD-031, ORD-030 and ORD-029, in that order.

Sort by date and a second field

MongoDB orders the results by created_at first. When orders share a timestamp, it uses the unique _id as a tie-breaker. The query sorts all matching documents before taking the first three. Set both values to 1 to reverse the order.

In KeplerGrid, open keplergrid_query_lab.orders in Documents using a Read only connection. Paste this into Filter.

{ "status": "paid" }

Open Sort & projection, paste this into Sort and click Run. The same three orders appear first in the grid.

{ "created_at": -1, "_id": -1 }

Sort in an aggregation pipeline

Open Aggregation → JSON on the same collection. Paste this pipeline and click Run pipeline. It filters the orders, sorts them and returns the same three rows.

[
  { "$match": { "status": "paid" } },
  { "$sort": { "created_at": -1, "_id": -1 } },
  { "$limit": 3 }
]

Use the same tie-breaker to page through results with a stable sort. To sort the elements of an array, use $sortArray.

Sort the first column and use Add to sort on the next header. Drag a field in the sort summary to change its priority without reversing it. Include a unique tie-breaker before paging. See how to sort, reverse or remove one field.