0

I'm struggling with a simple operation with the mongodb native driver for nodejs. Here is my mongo document:

{
    "_id" : 1,
    "foo" : "bar",
    "baz" : [
         {
            "a" : "b",
            "c" : 1
         },
         {
            "a" : "b",
            "c" : 2
         }
    ]
}

and I have a var like the following :

var removeIt = {"a" : "b", "c" : 1};

So to pull this object from the baz array I try to do the following :

collection.update(
        {_id:1}, 
        {$pull:{baz:{a:removeIt.a, c:removeIt.c}}},
        {safe:true},
        function(err, result) {}
);

But this doesn't seem to work, and I cannot get why, any idea?

2
  • I would think you would need to use: {$pull:{baz:{ removeIt }}}, instead - did you try that? Commented Nov 12, 2012 at 15:06
  • Thans for your comment, but this throws an error, and {$pull:{baz: removeIt }} just do nothing like my implementation. Commented Nov 12, 2012 at 15:10

1 Answer 1

3

I've just tried this on the MongoShell, and the following works for me:

> db.test.insert( {
    "_id" : 1,
    "foo" : "bar",
    "baz" : [
         {
            "a" : "b",
            "c" : 1
         },
         {
            "a" : "b",
            "c" : 2
         }
    ]
});

> db.test.findOne();
{ "_id" : 1, "baz" : [ { "a" : "b", "c": 1 }, { "a" : "b", "c" : 2 } ], "foo" : "bar" }

> removeIt = {"a" : "b", "c" : 1};
> db.test.update( { _id: 1 }, { $pull: { baz: removeIt } } );

> db.test.findOne();
{ "_id" : 1, "baz" : [ { "a" : "b", "c" : 2 } ], "foo" : "bar" }

So modify your:

{$pull:{baz:{a:removeIt.a, c:removeIt.c}}}

to:

{$pull:{baz: removeIt}}

And it should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it also works for me from the mongo shell, but not with the node-mongodb-native driver

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.