【问题标题】:How do I remove a string from an array in a mongodb document?如何从 mongodb 文档中的数组中删除字符串?
【发布时间】:2015-08-14 05:11:58
【问题描述】:

我一直遇到从 mongodb 文档中的数组中删除字符串的问题。例如,我想从下面文档的列表字段中删除条目“四”。

{
  "list" : [ "1", "2", "four", "five", "6"]
}

我知道这看起来很简单,但我无法从文档或以前的问题中找到直接答案。我使用 db.collection.update 结合 $pull 和 $mod 修饰符尝试了 5 个左右的命令,但均无济于事。有什么帮助吗?

我知道,非常初级的问题。

【问题讨论】:

标签: mongodb


【解决方案1】:

您可以使用$pull 运算符,请尝试以下查询:

db.collection.update({
    { _id : id },
    { $pull: { "list": "four" } }
});

如果您想从数组“列表”中删除两个或更多元素,您也可以使用 $pull 运算符:

db.collection.update({
    { _id : id },
    { $pull: { list : { $in : [ "one", "four" ] } } }
});

【讨论】:

  • 谢谢你这样做,我很惊讶我没有想到这一点。
猜你喜欢
  • 2022-11-27
  • 2020-06-08
  • 2013-07-23
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2022-01-18
相关资源
最近更新 更多