2

I want to remove a specific element from array stored in mongodb document. I am using this:

 model.registerCompany.findOneAndUpdate({companyKey:"a key"},
    {$pop:{onlineEmployees:"John"}},
    function(err,doc){
    if(!err)
        console.log("Online list modified: ",doc);
    else
        console.log("Online list modified error :",err);
});

But I am not sure if the $pop removes the specific element "John" from array(onlineEmployees) or just pop out the last element from it.

Am i doing it right or there is another way to do it.?

I think i got the answer .. $pull is used for this purpose as explained here in the link: http://docs.mongodb.org/manual/reference/operator/pull/#_S_pull

0

1 Answer 1

13

The $pop operator will remove first or last element of the array, which may not necessarily be the right one.

If you want a specific element, you can $pull the item with defined criteria:

   model.registerCompany.findOneAndUpdate({companyKey:"a key"},
    {$pull:{onlineEmployees:"John"}},

You have to make sure the value in the array is unique, for $pull removes every element matching the name 'John'.

If identical values exist in the array, you need to use $unset and $ positional operator to set the target element value to null(unfortunately $unset won't remove elements) and then use $pull to remove the element with null value. To do that, you have to make sure valid value can not be null. In that case, the code could be like:

model.registerCompany.findOneAndUpdate({companyKey:"a key", onlineEmployees:"John"},{ $unset: { "onlineEmployees.$" : '' } } ) 
model.registerCompany.findOneAndUpdate({companyKey:"a key"},{ $pull: { "onlineEmployees" : null } } ) 
Sign up to request clarification or add additional context in comments.

Comments

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.