How to remove a field from a document

Database Schema:

{ _id: "kun2", result150160: [10,20,30]; moon: 4 } 

I want to delete the entire result150160 field by the client with a variable:

 var deleteresult = "result150160" Box.update( {_id: this._id} , {$unset: { deleteresult } } ); 
+6
source share
3 answers

The correct syntax is as follows:

 Box.update( {_id: this._id} , {$unset: { deleteresult : "" } } ); 

You must specify a value for the operation $unset : { deleteresult : "" } . Even if it is empty.

Execute relevant documents :

db.collection.update( { field: value1 }, { $unset: { field1: "" } } );
The above example removes field1 in the collection from documents, where the field has the value value1. The value of the field in the $ unset expression (i.e., "" Above) does not affect the operation.

+12
source

You can do:

 var deleteresult = {}; deleteresult["result150160"] = true Box.update( {_id: this._id} , {$unset: deleteresult } ); 

Basically, you should use a pair of key values, no matter what you use for true , if there is something there.

+1
source

Try this, it should work for you:

 var deleteresult = "result150160"; var updateQuery={$unset:{}}; updateQuery.$unset[deleteresult]=1; Box.update( {_id: this._id} ,updateQuery,false,true); 
+1
source

Source: https://habr.com/ru/post/952719/


All Articles