Sling Academy
Home/Node.js/Mongoose updateMany() function explained (with examples)

Mongoose updateMany() function explained (with examples)

Last updated: December 30, 2023

Introduction

The updateMany() function in Mongoose is an essential tool used to modify multiple documents within a collection in a MongoDB database. This guide covers its purpose, syntax, and usage with practical examples.

Mongoose introduced updateMany() as part of its Query API to work with MongoDB, which has evolved to include such methods in various versions, particularly post the 4.x releases.

updateMany() is designed to update all documents that match a provided filter. This is useful for batch updates when you want to make the same change to multiple documents.

Syntax and Parameters

The basic syntax of updateMany() is:

Model.updateMany(filter, update, [options], [callback])

The parameters are:

  • filter – The selection criteria to match the documents you want to update.
  • update – The modifications to apply.
  • options (optional) – Additional options such as { upsert: true } to create a new document if no match is found.
  • callback (optional) – A function to execute upon completion. If omitted, a Promise is returned.

The returned value is a Promise if no callback is provided, resolving to an object containing the operation results.

Code Examples

Basic Usage

Update the status field of all documents matching the filter.

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({ name: String, status: String });
const User = mongoose.model('User', userSchema);

async function updateMultipleUsers() {
  await mongoose.connect('mongodb://localhost:27017/myapp');
  const result = await User.updateMany({ status: 'active' }, { $set: { status: 'inactive'} });
  console.log(result);
}

updateMultipleUsers();

With Options

Use upsert option to create new documents if none match the filter.

async function updateOrInsertUsers() {
  const result = await User.updateMany(
    { status: 'unknown' },
    { $set: { status: 'newcomer'} },
    { upsert: true }
  );
  console.log(result);
}

updateOrInsertUsers();

Conclusion

The updateMany() function is a powerful aspect of Mongoose that allows for bulk updates to documents in a MongoDB collection. Understanding its use is key for efficient database operations.

Next Article: Mongoose: Find documents since last day, last week, last month

Previous Article: Mongoose: Find Documents Between Two Dates (Inclusive)

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