0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find and Sort Documents

Use db.collection.find(query).sort({field: 1}) to find documents matching query and sort them by field in ascending order; use -1 for descending order.
📋

Examples

InputFind all users and sort by age ascending
Output[{ "name": "Anna", "age": 22 }, { "name": "Bob", "age": 30 }, { "name": "Cara", "age": 35 }]
InputFind users with age > 25 and sort by name descending
Output[{ "name": "Cara", "age": 35 }, { "name": "Bob", "age": 30 }]
InputFind users with name 'John' and sort by age ascending
Output[]
🧠

How to Think About It

To find and sort documents, first decide what filter you want to apply using find(). Then, use sort() to order the results by one or more fields, specifying 1 for ascending or -1 for descending order.
📐

Algorithm

1
Get the collection to query.
2
Apply the filter criteria using <code>find()</code>.
3
Apply sorting using <code>sort()</code> with the desired field and order.
4
Return the sorted list of documents.
💻

Code

mongodb
db.users.insertMany([
  { name: "Bob", age: 30 },
  { name: "Anna", age: 22 },
  { name: "Cara", age: 35 }
]);

const results = db.users.find({}).sort({ age: 1 }).toArray();
printjson(results);
Output
[ { "_id": ObjectId("..."), "name": "Anna", "age": 22 }, { "_id": ObjectId("..."), "name": "Bob", "age": 30 }, { "_id": ObjectId("..."), "name": "Cara", "age": 35 } ]
🔍

Dry Run

Let's trace finding all users and sorting by age ascending.

1

Insert sample users

[{ name: "Bob", age: 30 }, { name: "Anna", age: 22 }, { name: "Cara", age: 35 }]

2

Find all users

Returns all 3 users in any order

3

Sort users by age ascending

Orders users as Anna (22), Bob (30), Cara (35)

NameAge
Anna22
Bob30
Cara35
💡

Why This Works

Step 1: Find documents

The find() method filters documents matching the query criteria.

Step 2: Sort results

The sort() method orders the matched documents by the specified field and direction.

Step 3: Return sorted list

The final output is the list of documents sorted as requested.

🔄

Alternative Approaches

Aggregation pipeline with $match and $sort
mongodb
db.users.aggregate([
  { $match: { age: { $gt: 25 } } },
  { $sort: { name: -1 } }
]).toArray();
More flexible for complex queries but slightly more verbose.
Find with projection and sort
mongodb
db.users.find({}, { name: 1, age: 1, _id: 0 }).sort({ age: -1 }).toArray();
Returns only selected fields with sorting, useful to reduce data size.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting requires comparing documents, which takes O(n log n) time for n documents.

Space Complexity

The query stores matched documents in memory before sorting, so space is O(n).

Which Approach is Fastest?

Using find().sort() is efficient for simple queries; aggregation is better for complex filtering and sorting.

ApproachTimeSpaceBest For
find().sort()O(n log n)O(n)Simple find and sort
Aggregation pipelineO(n log n)O(n)Complex queries with multiple stages
Find with projection and sortO(n log n)O(n)Reducing returned fields with sorting
💡
Use 1 for ascending and -1 for descending order in sort().
⚠️
Forgetting to call toArray() or iterate the cursor to see results.