Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove a specified field from all documents of a collection using mongoose?

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  }
like image 471
Haris KK Avatar asked Apr 13 '17 11:04

Haris KK


People also ask

How do I remove a field from all files in a collection MongoDB?

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.

How do I select a single field for all documents in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do you delete an item from MongoDB using mongoose?

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.


1 Answers

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 }
like image 143
AshokGK Avatar answered Oct 24 '22 14:10

AshokGK