I want to remove key "passwrod" from all documents from users collection using mongoose , is it possible to do it using $unset ?
{ "_id" : ObjectId("58ec890c91b2b612084fd827"),
"username" : "zain",
"passwrod" : 123,
"password" : 8 },
{ "_id" : ObjectId("58ec8918364116187845948d"),
"username" : "bob",
"password" : 123,
"passwrod" : 12 }
In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.
Documents:
{ "_id" : ObjectId("58ec890c91b2b612084fd827"), "username" : "zain", "passwrod" : 123, "password" : 8 }
{ "_id" : ObjectId("58ec8918364116187845948d"), "username" : "bob", "password" : 123, "passwrod" : 12 }
Query:
db.collection.updateMany({}, {$unset:{"passwrod":1}})
Result:
{ "_id" : ObjectId("58ec890c91b2b612084fd827"), "username" : "zain", "password" : 8 }
{ "_id" : ObjectId("58ec8918364116187845948d"), "username" : "bob", "password" : 123 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With