mongodb findone and update code example

Example 1: mongodb updateone

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

Example 2: mongofindoneandupate

try {
db.grades.findOneAndUpdate(
   { "name" : "A.B. Abracus" },
   { $set: { "name" : "A.B. Abracus", "assignment" : 5}, $inc : { "points" : 5 } },
   { sort: { "points" : 1 }, upsert:true, returnNewDocument : true }
);
}
catch (e){
   print(e);
}

Example 3: returned value by findOneAndUpdate

const filter = { age: 17 };
const doc = { $set: { name: "Naomi" } };
const options = { new: true };

Cat.findOneAndUpdate(filter, doc, options, (err, doc) => {
    if (err) console.log("Something wrong when updating data!");
    console.log(doc);
});

Example 4: mongoid find_one_and_update

Model.where(id: id).find_one_and_update({
    :$inc => {
      payload
    }
  },
  upsert: true,
  return_document: :after
)

Example 5: 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}`))

Example 6: mongodb findoneandupdate return updated

//pass the {new: true} as the third option, if using mongodb driver use {returnOriginal: true}                                                      V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});