23.03.2020 Views

node-js

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

db.food.updateMany(

{ sold: { $lt: 10 } },

{ $set: { sold: 55 } }

)

This operation updates all documents (in a 'food' collection) where sold is lesser than 10 *(1st

parameter) by setting sold to 55. It then returns a WriteResult object that looks like this:

{ "acknowledged" : true, "matchedCount" : a, "modifiedCount" : b }

a = Number of matched documents

b = Number of modified documents

ReplaceOne

Replaces the first matching document (replacement document)

This example collection called countries contains 3 documents:

{ "_id" : 1, "country" : "Sweden" }

{ "_id" : 2, "country" : "Norway" }

{ "_id" : 3, "country" : "Spain" }

The following operation replaces the document { country: "Spain" } with document { country:

"Finland" }

db.countries.replaceOne(

{ country: "Spain" },

{ country: "Finland" }

)

And returns:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The example collection countries now contains:

{ "_id" : 1, "country" : "Sweden" }

{ "_id" : 2, "country" : "Norway" }

{ "_id" : 3, "country" : "Finland" }

Deleting

Deleting documents from a collection in mongoose is done in the following manner.

Auto.remove({_id:123}, function(err, result){

if (err) return console.error(err);

https://riptutorial.com/ 212

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!