问题
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
回答1:
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 } } )
来源:https://stackoverflow.com/questions/14472858/removing-an-element-from-array-in-mongodb