Sling Academy
Home/Node.js/Mongoose: Retrieving the Latest Document

Mongoose: Retrieving the Latest Document

Last updated: December 30, 2023

Let’s explore some different techniques to retrieve the latest document in a MongoDB collection by using Mongoose.

Solution 1: Using Sort and Limit

This solution involves sorting the documents by their creation date in descending order and limiting the result to one, effectively getting the latest document.

Steps:

  • Step 1: Establish a connection to the MongoDB database using Mongoose.
  • Step 2: Define your Mongoose schema and model if not already defined.
  • Step 3: Use the find() method with sort() and limit() to retrieve the newest document.

Code example:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const connectDatabase = async () => {
  await mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
};

const mySchema = new Schema({ createdAt: Date });
const MyModel = mongoose.model('MyModel', mySchema);

const getLatestDocument = async () => {
  return MyModel.find().sort({ createdAt: -1 }).limit(1).exec();
};

// Usage
connectDatabase().then(async () => {
  const latestDoc = await getLatestDocument();
  console.log(latestDoc);
});

Pros: Straightforward approach using native Mongoose methods; easy to understand and implement.

Cons: Introduces overhead with sorting, especially on large datasets.

Solution 2: Aggregation with $sort and $limit

This method uses the aggregation pipeline to sort the documents and then get the topmost document, which is the latest.

Steps:

  • Step 1: Establish a connection to your MongoDB database using Mongoose.
  • Step 2: Define your Mongoose schema and model if it’s not already in place.
  • Step 3: Use the aggregation framework with $sort and $limit to retrieve the most recent document.

A basic example:

const mySchema = new Schema({ createdAt: Date });
const MyModel = mongoose.model('MyModel', mySchema);

const getLatestDocumentUsingAggregation = async () => {
  return MyModel.aggregate([
    { $sort: { createdAt: -1 } },
    { $limit: 1 }
  ]).exec();
};

// Usage
connectDatabase().then(async () => {
  const latestDoc = await getLatestDocumentUsingAggregation();
  console.log(latestDoc);
});

Pros: High performance; optimal for large datasets because it pushes the work to the database server.

Cons: More complex than the first solution, might require deeper knowledge of the aggregation framework.

Solution 3: findOne with Sort

Description: This technique utilizes the findOne() method together with a sort condition to retrieve the most recent document from the collection.

Steps:

  • Step 1: Set up a connection to the mongo database with Mongoose.
  • Step 2: Outline your schema and create the model if that step hasn’t been done yet.
  • Step 3: Make use of the findOne() method along with sort to fetch the latest document.

A quick example:

const mySchema = new Schema({ createdAt: Date });
const MyModel = mongoose.model('MyModel', mySchema);

const getLatestDocumentUsingFindOne = async () => {
  return MyModel.findOne().sort({ createdAt: -1 }).exec();
};

// Usage
connectDatabase().then(async () => {
  const latestDoc = await getLatestDocumentUsingFindOne();
  console.log(latestDoc);
});

Pros: Simple and concise solution; it does what is needed without extra steps.

Cons: Might not be the most optimized for performance on very large collections.

Conclusion

There are multiple ways to retrieve the latest document from a MongoDB collection using Mongoose. Choosing the right one depends on the specific needs and context of the usage scenario. For most general use cases, using sort and limit functions is sufficient, but when dealing with larger datasets or specific performance requirements, the aggregation pipeline may offer improved performance.

Next Article: Mongoose: How to find and update subdocuments

Previous Article: Mongoose: How to safely change schema in production

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates