Sling Academy
Home/MongoDB/MongoDB: Sorting Documents by Updated Time

MongoDB: Sorting Documents by Updated Time

Last updated: February 03, 2024

Introduction

MongoDB, a NoSQL database, is popular for its flexibility and scalability. It stores data in JSON-like documents that can have varied structures. When working with data, sorting documents by updated time can be a common requirement, be it for generating reports, displaying recent updates, or simply organizing your findings. In this tutorial, we’ll explore how to achieve this with multiple code examples.

Prerequisites

  • Basic understanding of MongoDB and its query language.
  • MongoDB server installed and running.
  • MongoDB Compass or another database management tool.
  • A collection with documents that include an updated timestamp field.

Adding an Updated Time Field

Before we dive into sorting documents, ensure that your documents have a field that tracks the last updated time. This is typically achieved with a timestamp field:

db.collection.update(
  { },
  { $set: { updatedAt: new Date() } },
  { multi: true }
)

The above operation will add an updatedAt field with the current date and time to all documents within the collection.

Basic Sorting by Updated Time

Sorting in MongoDB is done using the sort() method. To sort documents by the updatedAt field in descending order (newest first):

db.yourCollectionName.find().sort({ updatedAt: -1 })

This returns a cursor that when iterated over, will yield the documents sorted by the updatedAt field.

For ascending order (oldest first):

db.yourCollectionName.find().sort({ updatedAt: 1 })

Sorting with Projection

Sometimes, you might want to retrieve only certain fields of your documents when sorting. This can be done with projection:

db.yourCollectionName.find({}, { content: 1 }).sort({ updatedAt: -1 })

This will return only the content field of your sorted documents.

Sorting within Aggregation Pipelines

MongoDB’s aggregation framework is a powerful feature that allows for complex data aggregation operations. Here’s how you can sort documents within an aggregation pipeline:

db.yourCollectionName.aggregate([
  { $match: {} },
  { $sort: { updatedAt: -1 } }
])

The $match stage is used to filter documents, and the $sort stage immediately follows it to sort the resulting documents.

Indexing the Updated Time Field

As your collection grows, sorting operations can become slower. To maintain performance, create an index on the updatedAt field:

db.yourCollectionName.createIndex({ updatedAt: -1 })

Handling Dates in Different Time Zones

MongoDB stores times in UTC by default. If you have to deal with multiple time zones, consider converting times to UTC before storing them or using the $dateToString operator within the aggregation pipeline when sorting.

Advanced Sorting: Combined Criteria

Besides sorting by the updated time, sometimes, you might need to sort by multiple criteria. Here’s how to sort documents by updated time, then by title:

db.yourCollectionName.find().sort({ updatedAt: -1, title: 1 })

Pagination with Sorting

When displaying results, especially in web applications, you often paginate your data. Here’s how you would implement pagination:

const pageSize = 10;
const page = 1; // Assuming the first page

db.yourCollectionName.find()
  .sort({ updatedAt: -1 })
  .skip(pageSize * (page - 1))
  .limit(pageSize)

Performance Considerations

Always monitor the performance of your sort operations, especially on large datasets. The use of indexes, as mentioned earlier, is crucial for ensuring that your sort queries are efficient and perform well at scale.

Conclusion

Sorting documents by updated time in MongoDB is a straightforward operation that can be customized and optimized for different use cases. Whether within simple queries or complex aggregation pipelines, maintaining performance through effective indexing should always be a priority.

Next Article: When not to use MongoDB? Here’re 7 common scenarios

Previous Article: MongoDB: Using Vermongo to track document history (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)