mongodb update one code example

Example 1: mongodb updateone

db..updateOne({ id : 8400704 },{ $set: { name : "John" } })

Example 2: mongodb update

db.collectionName.update({"aField":"vale1"},{$set:{"anotherField":"value2"}})

-search for documentations for more examples than search
-aField is used to find the documents
-anotherField is the field that will be updated
-You can also use the below:
-- updateOne
-- findOneAndUpdate

Example 3: updateone mongodb examples

const query = { "name": "football" };
const update = {
  "$push": {
    "reviews": {
      "username": "tombradyfan",
      "comment": "I love football!!!"
    }
  }
};
const options = { "upsert": false };

itemsCollection.updateOne(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
      console.log(`Successfully added a new review.`)
    }
  })
  .catch(err => console.error(`Failed to add review: ${err}`))

Tags:

Misc Example