<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr" -->

---
title: Aggregation Optimization in MongoDB: Sorting With...
description: This final installment of a five-part MongoDB optimization series shows how replacing an explicit $sort stage with an index-backed sort improved performance....
canonical: https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Aggregation Optimization in MongoDB: Sorting With Indexes (Part 5) | daily.dev
og:description: This final installment of a five-part MongoDB optimization series shows how replacing an explicit $sort stage with an index-backed sort improved performance....
og:url: https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr
og:image: https://api.daily.dev/og/posts/uBdqt9ZdR.png
og:image:alt: Aggregation Optimization in MongoDB: Sorting With Indexes (Part 5)
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Aggregation Optimization in MongoDB: Sorting With Indexes (Part 5)

**[Foojay.io](https://daily.dev/sources/foojayio)** · 6 min read · 1 upvotes · 0 comments

## Summary

This final installment of a five-part MongoDB optimization series shows how replacing an explicit $sort stage with an index-backed sort improved performance. By adding profileID to a compound index following the Equality-Sort-Range (ESR) rule, the pipeline avoided in-memory sorting of matched documents. Average query time dropped from 51ms to 14ms, and total time for 300 iterations fell from 1.2 seconds to 655 milliseconds, capping off a cumulative 230x+ improvement from the original 11.8-second pipeline.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://foojay.io/today/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5>

## Questions this post answers

### How can I avoid an in-memory sort in a MongoDB aggregation pipeline?

Add the sort field to a compound index instead of using an explicit $sort stage, since indexes return documents already ordered by key. In one case, adding profileID to an existing compound index on city and device name eliminated the $sort stage entirely, cutting average query time from 51ms to 14ms and total time for 300 iterations from 1.2 seconds to 655 milliseconds.

_Track practical database performance techniques like this one on daily.dev as you tune MongoDB pipelines._

### What is the Equality, Sort, Range (ESR) rule in MongoDB indexing?

The ESR rule determines optimal field ordering in a compound index: fields used for equality matches should come first, followed by fields used for sorting, followed by fields used for range queries. Applying this rule, a compound index ordered as city, device name, then profileID let equality-matched documents be returned already sorted by profileID, removing the need for a separate sort stage.

_Developers designing compound indexes can follow ESR guidance surfaced through daily.dev's database coverage._

### How much can removing unnecessary $unwind stages and duplicating data improve a MongoDB aggregation pipeline's performance?

In one video-streaming-style use case, removing unnecessary $unwind stages, refactoring a many-to-many relationship, and duplicating device name data brought average query time down from 11.8 seconds to 51 milliseconds, a roughly 230x improvement, before index-based sorting further reduced it to 14ms.

_Follow multi-step MongoDB optimization case studies like this on daily.dev when tuning aggregation pipelines._

## Similar posts on daily.dev

- [Aggregation Optimization in MongoDB: A Case Study From the Field \(Part 1\)](https://daily.dev/posts/aggregation-optimization-in-mongodb-a-case-study-from-the-field-part-1--gzqybwhpz) · Foojay.io · 0 upvotes · 0 comments

---

Tags: [#database](https://daily.dev/tags/database), [#mongodb](https://daily.dev/tags/mongodb)

[View this post on daily.dev](https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"Aggregation Optimization in MongoDB: Sorting With Indexes (Part 5)","url":"https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr"},"datePublished":"2026-09-01T14:12:27.440Z","dateModified":"2026-09-01T14:12:54.508Z","description":"This final installment of a five-part MongoDB optimization series shows how replacing an explicit $sort stage with an index-backed sort improved performance....","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/eb1fb2748a8d0e7056484b44eb36763e?_a=AQAEuop","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/eb1fb2748a8d0e7056484b44eb36763e?_a=AQAEuop","isAccessibleForFree":true,"articleSection":"Foojay.io","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Foojay.io","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/1820f6a6ae944760aa322b67ed85f848","url":"https://daily.dev/sources/foojayio"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":1},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"database,mongodb","timeRequired":"PT6M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Foojay.io","item":"https://daily.dev/sources/foojayio"},{"@type":"ListItem","position":3,"name":"Aggregation Optimization in MongoDB: Sorting With Indexes (Part 5)"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/aggregation-optimization-in-mongodb-sorting-with-indexes-part-5--ubdqt9zdr#faq","mainEntity":[{"@type":"Question","name":"How can I avoid an in-memory sort in a MongoDB aggregation pipeline?","acceptedAnswer":{"@type":"Answer","text":"Add the sort field to a compound index instead of using an explicit $sort stage, since indexes return documents already ordered by key. In one case, adding profileID to an existing compound index on city and device name eliminated the $sort stage entirely, cutting average query time from 51ms to 14ms and total time for 300 iterations from 1.2 seconds to 655 milliseconds. Track practical database performance techniques like this one on daily.dev as you tune MongoDB pipelines."}},{"@type":"Question","name":"What is the Equality, Sort, Range (ESR) rule in MongoDB indexing?","acceptedAnswer":{"@type":"Answer","text":"The ESR rule determines optimal field ordering in a compound index: fields used for equality matches should come first, followed by fields used for sorting, followed by fields used for range queries. Applying this rule, a compound index ordered as city, device name, then profileID let equality-matched documents be returned already sorted by profileID, removing the need for a separate sort stage. Developers designing compound indexes can follow ESR guidance surfaced through daily.dev's database coverage."}},{"@type":"Question","name":"How much can removing unnecessary $unwind stages and duplicating data improve a MongoDB aggregation pipeline's performance?","acceptedAnswer":{"@type":"Answer","text":"In one video-streaming-style use case, removing unnecessary $unwind stages, refactoring a many-to-many relationship, and duplicating device name data brought average query time down from 11.8 seconds to 51 milliseconds, a roughly 230x improvement, before index-based sorting further reduced it to 14ms. Follow multi-step MongoDB optimization case studies like this on daily.dev when tuning aggregation pipelines."}}]}
```

