MongoDB Sort

The sort method in MongoDB allows you to organize query results in a specific order. Sorting is an essential feature when working with large datasets, helping you display data meaningfully, such as showing the most recent or highest-rated entries first.

What Is the sort Method in MongoDB?

The sort method is used to arrange documents in ascending or descending order based on one or more fields.

  1. Ascending Order: Represented by 1.
  2. Descending Order: Represented by -1.

For example:

  • { age: 1 } sorts by the age field in ascending order.
  • { age: -1 } sorts by the age field in descending order.

Key Features of MongoDB Sort

  • Multi-Field Sorting: Sort by multiple fields for more precise control.
  • Dynamic Sorting: Combine sort with filters and pagination for dynamic query results.
  • Index Optimization: Sorting is faster when the sorted fields are indexed.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass: Use either for database management.

Basic Syntax of sort

The general syntax is:

db.collectionName.find(query).sort(sortCriteria);
  • query: Filters documents before sorting (optional).
  • sortCriteria: Specifies the fields and sort order.

Method 1: Sorting in MongoDB Shell

Step 1: Open the MongoDB Shell

Run the following command:

mongosh

Step 2: Switch to a Database

Select the database:

use myDatabase

Step 3: Sort Documents by a Single Field

Sort users by age in ascending order:

db.users.find().sort({ age: 1 });

Sort users by age in descending order:

db.users.find().sort({ age: -1 });

Step 4: Sort by Multiple Fields

Sort by city (ascending) and then by age (descending):

db.users.find().sort({ city: 1, age: -1 });

Method 2: Sorting in Node.js

Step 1: Install MongoDB Driver

Run the following command to install the MongoDB driver:

npm install mongodb

Step 2: Sort Documents in Node.js

Create a file named app.js and write the following code:

Sort by a Single Field

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myDatabase';

async function main() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected successfully to MongoDB');

// Select the database and collection
const db = client.db(dbName);
const collection = db.collection('users');

// Sort by age in ascending order
const users = await collection.find().sort({ age: 1 }).toArray();
console.log('Users sorted by age (ascending):', users);
} catch (err) {
console.error('Error sorting documents:', err);
} finally {
// Close the connection
await client.close();
}
}

main();

Sort by Multiple Fields

async function sortMultipleFields() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');

// Sort by city (ascending) and age (descending)
const users = await collection.find().sort({ city: 1, age: -1 }).toArray();
console.log('Users sorted by city and age:', users);
} catch (err) {
console.error('Error sorting documents:', err);
} finally {
await client.close();
}
}

sortMultipleFields();

Method 3: Sorting in MongoDB Compass

Step 1: Open MongoDB Compass

  1. Launch Compass and connect to your MongoDB server (mongodb://localhost:27017).
  2. Select your database and collection.

Step 2: Apply Sorting

  1. Click on the “Filter” tab.
  2. In the “Sort” box, enter the sorting criteria, e.g., { age: 1 } for ascending or { age: -1 } for descending.
  3. Click “Apply” to view the sorted results.

Advanced Sorting Techniques

1. Combine Sort with Limit

Retrieve the top 5 oldest users:

const users = await collection.find().sort({ age: -1 }).limit(5).toArray();
console.log('Top 5 oldest users:', users);

2. Sort Nested Fields

If your documents have nested fields, you can sort by them:

const users = await collection.find().sort({ 'address.zipcode': 1 }).toArray();
console.log('Users sorted by zipcode:', users);

3. Sort with Query Filters

Find users older than 30 and sort them by name:

const users = await collection.find({ age: { $gt: 30 } }).sort({ name: 1 }).toArray();
console.log('Users older than 30 sorted by name:', users);

Real-World Use Case

Imagine building a leaderboard for a gaming app where you need to display players ranked by their scores.

Example: Sorting Player Scores

async function sortLeaderboard() {
const db = client.db('game');
const collection = db.collection('players');

const leaderboard = await collection.find().sort({ score: -1 }).limit(10).toArray();
console.log('Top 10 players:', leaderboard);
}

sortLeaderboard();

Leave a Comment

BoxofLearn