mongodb set null in update

2019-02-22 13:37发布

问题:

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.

回答1:

Setting undefined, It worked like a charm!!

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