从mongodb中的数组中删除元素

从mongodb中的数组中删除元素

本文介绍了从mongodb中的数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从存储在 mongodb 文档中的数组中删除特定元素.我正在使用这个:

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);
});

但我不确定 $pop 是否从 array(onlineEmployees) 中删除了特定元素John",或者只是从中弹出最后一个元素.

我做对了还是有其他方法可以做到.?

我想我得到了答案.. $pull 用于此目的,如链接中所述:http://docs.mongodb.org/manual/reference/operator/pull/#_S_pull

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

推荐答案

$pop 运算符将删除数组的第一个或最后一个元素,这可能不一定是正确的.

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

如果你想要一个特定的元素,你可以$pull该项目具有定义的标准:

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

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

您必须确保数组中的值是唯一的,因为 $pull 会删除与名称 'John' 匹配的每个元素.

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

如果数组中存在相同的值,则需要使用$unset$位置运算符将目标元素值设置为null(不幸的是 $unset 不会删除元素)然后使用 $pull 删除具有 null 值的元素.为此,您必须确保有效值不能为 null.在这种情况下,代码可能类似于:

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 } } )

这篇关于从mongodb中的数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:16