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
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:
You have to make sure the value in the array is unique, for
$pullremoves every element matching the name ‘John’.If identical values exist in the array, you need to use
$unsetand$positional operator to set the target element value tonull(unfortunately $unset won’t remove elements) and then use$pullto remove the element withnullvalue. To do that, you have to make sure valid value can not benull. In that case, the code could be like: