0
0
MongoDBquery~5 mins

Index direction (ascending vs descending) in MongoDB

Choose your learning style9 modes available
Introduction

Indexes help find data faster in a database. The direction (ascending or descending) tells the database how to sort the data inside the index.

When you want to speed up searches that sort data from smallest to largest (ascending).
When you want to speed up searches that sort data from largest to smallest (descending).
When you create indexes for queries that use sorting to improve performance.
When you want to optimize queries that filter and sort on the same field.
When you want to control how data is stored in the index for better query speed.
Syntax
MongoDB
db.collection.createIndex({ fieldName: 1 })  // ascending index

db.collection.createIndex({ fieldName: -1 }) // descending index

Use 1 for ascending order and -1 for descending order.

The direction affects sorting and can improve query speed when used correctly.

Examples
This creates an ascending index on the age field, helping queries that sort or filter by age in ascending order.
MongoDB
db.users.createIndex({ age: 1 })
This creates a descending index on the orderDate field, helping queries that sort or filter by order date from newest to oldest.
MongoDB
db.orders.createIndex({ orderDate: -1 })
This creates a compound index: price ascending and rating descending. Useful for queries sorting by price ascending and rating descending.
MongoDB
db.products.createIndex({ price: 1, rating: -1 })
Sample Program

This example creates an ascending index on the price field in the products collection. Then it inserts some products and queries them sorted by price from low to high.

MongoDB
use shopDB

db.products.createIndex({ price: 1 })

// Insert sample data
 db.products.insertMany([
   { name: "Pen", price: 1.5 },
   { name: "Notebook", price: 3.0 },
   { name: "Pencil", price: 1.0 }
 ])

// Query sorted by price ascending
 db.products.find().sort({ price: 1 }).toArray()
OutputSuccess
Important Notes

Ascending and descending indexes both speed up queries, but choose direction based on how you sort your data.

MongoDB can use an ascending index for descending sorts and vice versa, but specifying direction helps optimize compound indexes.

Creating unnecessary indexes can slow down writes, so only create indexes you need.

Summary

Indexes store data in order: ascending (1) or descending (-1).

Choose index direction based on how you sort or filter your queries.

Compound indexes can mix ascending and descending directions for multiple fields.