如何从mongodb中的数组中删除元素

时间:2018-04-02 18:56:28

标签: mongodb mongodb-query

嗨,我有这样的结构。这是一个例子

{
    "_id" : "423dswar23ew2355",
    "competitions" : [ 
        "24",
        "58", 
        "354",
        "361"
    ],
}

如何从“competitions”数组中删除例如“58”项目。

我见过像

这样的解决方案
{ $pull: { competitions: { $eq: "58" }}}

但我的mongo说thar

  

MongoError:未知的顶级操作符:$ eq

所以任何人都可以提出一些更简单但同时工作的解决方案。提前致谢

3 个答案:

答案 0 :(得分:1)

请尝试以下代码:

db.col.update({_id: "423dswar23ew2355"}, { $pull: { "competitions": "58" } })

请记住,因为你有字符串,你应该将“58”作为字符串传递。

答案 1 :(得分:1)

这应该适用于新版本:

db.col.updateOne({_id: "423dswar23ew2355"}, { $pull: { "competitions": "58" } })

答案 2 :(得分:0)

如果要删除58,可以使用

db.lists.update({}, {$unset : {"competitions.2" : 1 }})

然后

db.lists.update({}, {$pull : {"competitions" : null}})

希望它可以帮到你