Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $unset and $set in combination in mongoDB

Tags:

mongodb

I have record like this :

{     "Date" : ISODate("2013-06-28T18:30:00Z"),     "Details" : {             "Amount1" : -200,             "Amount2" : 2800,             "Amount3" : -100     },     'NID' : 'T123RT',     'PID' : 'P123RT',     "SettAmount" : 2500,     "SettStatus" : "completed",     "Status" : "completed",     "StoreID" : "51ea54279d867b040b000008",     "_id" : ObjectId("51ea54279d867b040b000013") } 

I am trying to update the document like :

db.settlements.update({     'StoreID' : "51ea54279d867b040b000008",     'Date' : ISODate("2013-06-28T18:30:00Z") }, {     $unset : {         'NID' : "",         'PID' : ""     }     }, {     $set : {         'SettStatus' : 'start',         'Status' : 'pending'     } }); 

But, only unset operation is successful. what is the error in above query........?

like image 287
user550881 Avatar asked Jul 20 '13 09:07

user550881


People also ask

What does $unset do in MongoDB?

Description. In MongoDB, the $unset operator is used to delete a particular field. The value specified in the $unset expression does not make any impact on the operation. The $unset has no effect when the field does not exist in the document.

What does $Set do in MongoDB?

$set outputs documents that contain all existing fields from the input documents and newly added fields. The $set stage is an alias for $addFields . Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

How do I delete multiple records in MongoDB?

To delete multiple documents, use db. collection. deleteMany() .


1 Answers

you have too many braces, here's correct command:

db.settlements.update(     {         'StoreID': "51ea54279d867b040b000008",         'Date': ISODate("2013-06-28T18:30:00Z")     },      {         $unset: {             'NID' : "",             'PID' : ""         },          $set: {             'SettStatus': 'start',             'Status': 'pending'         }     } ); 

in your command, you're using $set as <options> in update command, not as part of <update>

http://docs.mongodb.org/manual/core/update/#crud-update-update

like image 75
Roman Pekar Avatar answered Oct 25 '22 05:10

Roman Pekar