$unset support in mongo node driver?

42 views
Skip to first unread message

Eric Fossas

unread,
Mar 28, 2017, 1:49:12 AM3/28/17
to mongodb-user
If I want to delete a key from a document using the mongo shell, I would use the following command:

db.collection.update({_id:"some_id"},{$unset:{"the.nested.key.to.delete":""}});


Is this supported in the mongo node driver? It doesn't seem to work. I tried:


db.collection('my_collection').update({_id:"some_id"},{$unset:{"the.nested.key.to.delete":""}},function(err,result) {

    // etc.

});


But that didn't work. I know I could find/retrieve the document, delete the key, then update it... but I'm not a fan of that approach. So is $unset supported, or is there another approach I should be using that I haven't thought of?

Kevin Adistambha

unread,
Apr 12, 2017, 2:48:33 AM4/12/17
to mongodb-user

Hi Eric,

Using the Node MongoDB driver version 2.2.25, this works for me:

> db.test.find()
{
  "_id": 0,
  "a": 1,
  "b": 2,
  "c": 3
}
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost/test', function(err, db) {
    db.collection('test').update({'_id': 0}, {'$unset': {'a': ''}}, function(err, res) {
        db.close();
    });
});
> db.test.find()
{
  "_id": 0,
  "b": 2,
  "c": 3
}

You might be missing quotes on the fields such as _id and $unset.

If it still doesn’t work for you, could you post:

  • Your MongoDB and your OS version
  • Your Node driver version
  • The complete code that you tried
  • Any error message that you see in mongod log, within node, etc.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages