ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Update in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1407' AND `tutorial_status`=1 LIMIT 1

Mongodb Update in NodeJs

Updating documents in MongoDB using Node.js can be done with:

  1. βœ… Native MongoDB Driver

  2. πŸͺ„ Mongoose (if you're using schemas)

Let’s see both in action πŸ‘‡


βœ… 1. Using the Native MongoDB Driver

πŸ“¦ Install MongoDB driver

bash

npm install mongodb


✍️ Update Code Example

js

const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);async function updateUser() { try { await client.connect(); const db = client.db('myDatabase'); const users = db.collection('users'); // πŸ‘‰ Update one user const updateOne = await users.updateOne( { name: 'Alice' }, // Filter { $set: { age: 30 } } // Update ); console.log('Updated one:', updateOne.modifiedCount); // πŸ‘‰ Update many users const updateMany = await users.updateMany( { age: { $lt: 25 } }, { $set: { status: 'young' } } ); console.log('Updated many:', updateMany.modifiedCount); } finally { await client.close(); }}updateUser();


πŸͺ„ 2. Using Mongoose

πŸ“¦ Install Mongoose

bash

npm install mongoose


✍️ Update Code Example

js

const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected'));const userSchema = new mongoose.Schema({ name: String, age: Number, status: String });const User = mongoose.model('User', userSchema);async function updateUserMongoose() { // πŸ‘‰ Update one user await User.updateOne({ name: 'Bob' }, { $set: { age: 32 } }); // πŸ‘‰ Update many users await User.updateMany({ age: { $lt: 20 } }, { status: 'teen' }); console.log('Updates complete'); mongoose.disconnect();}updateUserMongoose();


πŸ”§ Useful MongoDB Update Operators

OperatorMeaning
$setSet a new value
$incIncrement a value
$unsetRemove a field
$pushAdd item to an array
$pullRemove item from an array


🧠 Bonus: Update & Return the New Doc (Mongoose)

js

const updated = await User.findOneAndUpdate( { name: 'Alice' }, { age: 35 }, { new: true } // returns the updated document);console.log(updated);


Let me know if you’d like to:

  • Create an update API route

  • Use dynamic update values

  • Validate data before update

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql