iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

updateOne / updateMany

MongoDB’s update operators change documents in place — \$set, \$inc, \$push, \$pull. Atomic at the document level; idempotent if you design the operators right.

updateOne, updateMany, operators

EXAMPLE
// 1) Set / unset specific fields
await db.users.updateOne(
    { _id: userId },
    {
        $set:   { name: 'Ada', 'address.city': 'Melbourne' },
        $unset: { tempToken: '' },
    },
);

// 2) Increment counters atomically
await db.posts.updateOne(
    { _id: postId },
    { $inc: { views: 1, 'stats.likes': 1 } },
);

// 3) Push / pull from arrays
await db.users.updateOne(
    { _id: userId },
    { $push: { tags: 'newsletter' } },
);
await db.users.updateOne(
    { _id: userId },
    { $pull: { tags: { $in: ['old', 'expired'] } } },
);
await db.users.updateOne(
    { _id: userId },
    { $addToSet: { tags: 'unique' } },   // no duplicates
);

// 4) Update many — be careful, no LIMIT in mongo
const { modifiedCount } = await db.users.updateMany(
    { lastSeen: { $lt: thirtyDaysAgo } },
    { $set: { status: 'inactive' } },
);

// 5) Upsert — insert if no match
await db.counters.updateOne(
    { name: 'orders' },
    { $inc: { value: 1 } },
    { upsert: true },
);

// 6) Find AND modify in one round-trip
const doc = await db.jobs.findOneAndUpdate(
    { status: 'queued' },
    { $set: { status: 'running', startedAt: new Date() } },
    { sort: { createdAt: 1 }, returnDocument: 'after' },
);

// 7) Update array elements that match a condition
await db.orders.updateOne(
    { _id: orderId, 'items.sku': 'A-100' },
    { $set: { 'items.$.qty': 5 } },                     // first match
);
await db.orders.updateOne(
    { _id: orderId },
    { $set: { 'items.$[item].qty': 5 } },
    { arrayFilters: [{ 'item.sku': 'A-100' }] },        // ALL matches
);

// 8) Aggregation-pipeline updates (4.2+) — refer to other fields
await db.users.updateOne(
    { _id: userId },
    [
        { $set: { full: { $concat: ['$first', ' ', '$last'] } } },
    ],
);

Why it matters

Use update operators — never read-modify-write. \$inc, \$set, and friends are atomic at the document level, so two concurrent updates don’t step on each other.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
db.customers.updateOne(
    { _id: id },
    { $set: { email: 'new@example.com' }, $inc: { logins: 1 } }
);
Try it Yourself »

Discussion

Loading…