updateOne and updateMany With $set and $unset
Learners will modify specific fields in one or many documents without replacing the entire document.
The Two Main Update Methods
MongoDB provides two primary methods for modifying existing documents:
- updateOne(filter, update, options) — modifies the first document matching the filter. If multiple documents match, only one is updated.
- updateMany(filter, update, options) — modifies all documents matching the filter.
Both methods return a result object with matchedCount (how many documents matched the filter) and modifiedCount (how many were actually changed—some matching documents may already have the target value). Always verify modifiedCount in your application logic.
// updateOne: modify a specific document
const result = await db.collection('users').updateOne(
{ email: 'alice@example.com' }, // filter
{ $set: { lastLoginAt: new Date() } } // update
);
console.log(result.matchedCount); // 1
console.log(result.modifiedCount); // 1
// updateMany: modify all matching documents
const bulkResult = await db.collection('users').updateMany(
{ emailVerified: false },
{ $set: { needsVerification: true } }
);$set: Modifying Specific Fields
The $set operator sets the value of one or more fields. If a field does not exist, $set creates it. If it already exists, $set replaces its value. Only the specified fields are changed—all other fields in the document remain untouched.
This is the most important update operator and the one you will use in the vast majority of update operations. Never pass a plain document as the update argument without an operator—doing so replaces the entire document, losing all other fields.
// $set updates only the specified fields
db.users.updateOne(
{ _id: userId },
{ $set: { name: 'Alice Smith', updatedAt: new Date() } }
);
// Only 'name' and 'updatedAt' change; all other fields are preserved
// $set creates the field if it doesn't exist:
db.users.updateOne(
{ _id: userId },
{ $set: { newsletterOptIn: true } } // Added to doc even if it wasn't there
);
// $set on a nested field:
db.users.updateOne(
{ _id: userId },
{ $set: { 'address.city': 'New York' } } // Dot notation for nestedAll lessons in this course
- updateOne and updateMany With $set and $unset
- Increment, Multiply, and Min/Max Operators
- Array Update Operators: $push, $pull, $addToSet
- Deleting Documents Safely With deleteOne and deleteMany