Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a field from a document

Tags:

mongodb

meteor

The database schema:

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

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

var deleteresult = "result150160"
Box.update( {_id: this._id} , {$unset: { deleteresult } } );
like image 201
Sebastian Avatar asked Aug 29 '13 08:08

Sebastian


People also ask

How do I remove fields from a Word document?

Press CTRL+A on your keyboard to select all the text within the document. Right-click, then click Toggle Field Codes. Press CTRL+SHIFT+F9 on your keyboard. This will remove the field codes, replacing them with the text they contained.

How do you remove a field?

In the Navigation Pane, right-click the table, and then click Design View. In the table design grid, select the field that you want to delete, and then press DEL.

How do I remove a field from a document in 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.


3 Answers

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);
like image 28
Anuj Aneja Avatar answered Nov 15 '22 11:11

Anuj Aneja


The correct syntax is this:

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

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

Checkout the relevant docs:

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

like image 50
Lix Avatar answered Nov 15 '22 09:11

Lix


You could do:

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

Basically you have to use a key value pair, it doesn't matter what you use for true, as long as theres something there.

like image 35
Tarang Avatar answered Nov 15 '22 09:11

Tarang