๐Ÿง  Node.js โ€“ MongoDB: Advanced Queries
Estimated reading: 3 minutes 27 views

๐Ÿ”ข Node.js โ€“ MongoDB Sort โ€“ Organize Query Results by Fields Using Node.js


๐Ÿงฒ Introduction โ€“ Why Use Sort in MongoDB with Node.js?

Sorting is a critical feature when displaying lists, leaderboards, logs, or any ordered data. MongoDB allows you to sort documents by any field using the sort() method. Node.js developers can easily sort MongoDB results in ascending or descending order while querying collections.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to sort MongoDB documents using Node.js
  • Sort results in ascending (1) or descending (-1) order
  • Combine sorting with limit(), skip(), and filters
  • Best practices to optimize sorting with indexes

โš™๏ธ Setup โ€“ MongoDB Connection File (db.js)

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

const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const dbName = 'appDB';

async function getDB() {
  await client.connect();
  console.log('โœ… Connected to MongoDB');
  return client.db(dbName);
}

module.exports = getDB;

๐Ÿ”ข Sort Documents by One Field โ€“ Ascending

const getDB = require('./db');

async function sortUsersByAge() {
  const db = await getDB();
  const users = await db.collection('users')
    .find({})
    .sort({ age: 1 }) // Ascending
    .toArray();

  console.log('๐Ÿ“‹ Users sorted by age:', users);
}

sortUsersByAge();

๐Ÿงช Output:

๐Ÿ“‹ Users sorted by age: [{ name: "Amy", age: 21 }, { name: "Bob", age: 24 }, ...]

โœ… 1 sorts in ascending order.


๐Ÿ”ป Sort by One Field โ€“ Descending

const users = await db.collection('users')
  .find({})
  .sort({ age: -1 }) // Descending
  .toArray();

โœ… -1 sorts in descending order.


๐Ÿงฎ Sort by Multiple Fields

const users = await db.collection('users')
  .find({})
  .sort({ role: 1, age: -1 }) // Sort by role ASC, then age DESC
  .toArray();

๐Ÿ“Œ Useful for grouping and then sorting within groups.


๐Ÿ” Combine with limit() and skip() for Pagination

const users = await db.collection('users')
  .find({})
  .sort({ createdAt: -1 })
  .skip(10)
  .limit(5)
  .toArray();

โœ… Skips the first 10 results, returns the next 5 sorted by creation date (most recent first).


๐Ÿงฑ Best Practices for Sorting in MongoDB with Node.js

โœ… Practice๐Ÿ’ก Why Itโ€™s Useful
Use indexes on sorted fieldsImproves query performance
Limit result set when paginatingAvoids memory overload
Always define sort order clearlyAvoids default or unexpected sorting
Combine sort with projectionOnly fetch necessary fields
Donโ€™t sort on non-indexed large fieldsCan slow down queries significantly

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Sorting MongoDB results with Node.js helps build clean, user-friendly applications. Whether ordering products, blog posts, or scoresโ€”use sort() wisely with filters and indexes.

๐Ÿ” Key Takeaways:

  • Use sort({ field: 1 }) for ascending, -1 for descending
  • Chain with limit() and skip() for pagination
  • Combine multiple sort fields for grouped order
  • Always index the fields you sort by for speed

โš™๏ธ Real-world relevance:
Used in dashboards, tables, e-commerce listings, feeds, notifications, and log viewers.


โ“FAQs โ€“ Sorting MongoDB Data in Node.js


โ“ How do I sort documents by date?
โœ… Use:

.sort({ createdAt: -1 }) // Newest first

โ“ Can I sort by two fields?
โœ… Yes:

.sort({ category: 1, price: -1 })

โ“ What happens if I donโ€™t specify sort order?
โœ… MongoDB returns documents in natural order (insertion sequence), which is not guaranteed.


โ“ Do I need indexes for sorting?
โœ… No, but itโ€™s highly recommended for large datasets. Sorting without indexes can slow down performance.


โ“ Can I sort on nested fields?
โœ… Yes, using dot notation:

.sort({ 'profile.age': 1 })

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”ข Node.js โ€“ MongoDB Sort

Or Copy Link

CONTENTS
Scroll to Top