Home / Articles / Database / mongodb / 5.0 / update

MongoDB Update Statement

Open MongoDB Shell

  • Open the MongoDB Shell from Linux shell
  • # mongosh Current Mongosh Log ID: 6117225c105379b62b6abaa9 Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000 Using MongoDB: 5.0.2 Using Mongosh: 1.0.5 For mongosh info see: https://docs.mongodb.com/mongodb-shell/ test>
  • Switch to our "employee" database
  • # use employee switched to db employee

Update Single Record

  • Run following command to update one record to "emp_info" collection
  • employee> db.emp_info.updateOne( { first:"Sam" }, { $set: { role:"Senior Manager"} } ) { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

    Show the updated records

    employee> db.emp_info.find( { first:"Sam" } ) [ { _id: ObjectId("61172c1ca1766234eab5b87f"), first: 'Sam', last: 'Doe', role: 'Senior Manager', } ]

Add New Field to All Existing Collection

  • Run following command to add field "Country" to all the existing records in collection "emp_info"
  • employee> db.emp_info.updateMany ( {}, { $set: { country:"USA" } } ) { acknowledged: true, insertedId: null, matchedCount: 3, modifiedCount: 3, upsertedCount: 0 }

    Show the updated records

    employee> db.emp_info.find() [ { _id: ObjectId("61172935a1766234eab5b87a"), first: 'John', last: 'Davis', role: 'Dev', country: 'USA' }, { _id: ObjectId("61172c1ca1766234eab5b87e"), first: 'Allan', last: 'Coller', role: 'CM', country: 'USA' }, { _id: ObjectId("61172c1ca1766234eab5b87f"), first: 'Sam', last: 'Doe', role: 'Senior Manager', country: 'USA' } ]

Update Multiple Records

  • Run following command to update "country" field value for all records
  • employee> db.emp_info.updateMany ( { country:"USA" }, {$set: { country:"United States of America" } } ) { acknowledged: true, insertedId: null, matchedCount: 3, modifiedCount: 3, upsertedCount: 0 }

    Show the updated records

    employee> db.emp_info.find() [ { _id: ObjectId("61172935a1766234eab5b87a"), first: 'John', last: 'Davis', role: 'Dev', country: 'United States of America' }, { _id: ObjectId("61172c1ca1766234eab5b87e"), first: 'Allan', last: 'Coller', role: 'CM', country: 'United States of America' }, { _id: ObjectId("61172c1ca1766234eab5b87f"), first: 'Sam', last: 'Doe', role: 'Senior Manager', country: 'United States of America' } ]