Introduction
Learn how to update documents in a MongoDB collection using the mongosh shell interface.
Connecting to MongoDB
Before updating documents, ensure you are connected to your MongoDB server:
Example: Connecting to MongoDB
mongoshThis command starts the mongosh shell and connects to the default MongoDB server running locally.
Switching to a Database
Switch to the database where your collection resides using the use command:
Example: Switching to a Database
use mydatabaseThis command switches to the “mydatabase” database. Replace mydatabase with your database name.
Updating Documents
To update documents in a MongoDB collection, use the updateOne or updateMany methods:
Example: Updating a Single Document
db.mycollection.updateOne(
{ name: "John Doe" },
{ $set: { status: "inactive" } }
)This command updates a single document in the mycollection collection where the name field equals “John Doe”, setting the status field to “inactive”.
Example: Updating Multiple Documents
db.mycollection.updateMany(
{ status: "active" },
{ $set: { status: "inactive" } }
)This command updates multiple documents in the mycollection collection where the status field equals “active”, setting the status field to “inactive”.
Updating with Operators
Use update operators for more complex updates:
Example: Using Update Operators
db.mycollection.updateOne(
{ name: "Alice Smith" },
{ $inc: { age: 1 } }
)This command increments the age field of the document where the name field equals “Alice Smith” by 1.
Verifying Updates
Verify that the documents have been updated by querying the collection:
Example: Verifying Updates
db.mycollection.find()This command retrieves all documents from the mycollection collection. Check that your updates have taken effect.
Conclusion
Updating documents in a MongoDB collection using mongosh provides flexibility to modify existing data based on specific criteria. Experiment with different update methods and operators to suit your application’s needs.