Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb set null in update

I have to interchange the values of a document.

var query = {"_id" : ObjectId("53e1c254382f891cc600076d")};

db.properties.find(query).forEach(function(prop){
   printjson({"_id":prop._id, "val":prop.val, "ua":prop.ua});
   db.properties.update(query, {$set:{ua: prop.val}},{$unset:{val:""}});
});

Before update operation, document looks like this:

{
    "_id" : ObjectId("53e1c254382f891cc600076d"),
    "val" : 9876541,
    "ua" : null
}

And after the update it turns to:

{
    "_id" : ObjectId("53e1c254382f891cc600076d"),
    "val" : 9876541,
    "ua" : 9876541
}

But I expect it as:

{
    "_id" : ObjectId("53e1c254382f891cc600076d"),
    "val" : null,
    "ua" : 9876541
}

But its not working. also setting "val" null ({$set:{val:null}}) directly it deleted my entire document.

like image 247
trex Avatar asked May 08 '15 11:05

trex


People also ask

Can we insert null in MongoDB?

Indeed, it's not possible to store null values in a MongoDB document using a DataFrame. The Python None values are considered as missing attributes accordingly to this NoSQL specific allowance. However, if your column is numerical, you can force writing a null value by setting it to NaN.

How do I update a specific field in MongoDB?

We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

Can we update _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.

How do I ignore NULL values in MongoDB?

Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .


1 Answers

Setting undefined, It worked like a charm!!

db.properties.find(query).forEach(function(prop){
    db.properties.update(query, {$set:{ua: prop.val, val:undefined}}); 
});
like image 181
trex Avatar answered Sep 22 '22 18:09

trex