【问题标题】:Deleting items from the array of objects从对象数组中删除项目
【发布时间】:2021-08-01 23:11:51
【问题描述】:

我有一个看起来像这样的文档:

{
  _id: "....",
  hostname: "mysite.com",
  text: [
    {
        source: "this is text. this is some pattern",
        ...
    },
    {
        source: "....",
        ...
     }
  ]
}

我正在尝试从text 数组中删除与我的查询中的特定条件匹配的项目:

db.getCollection('TM').updateMany(
  {hostname: "mysite.com"},
  {
    $pull: {
            "text.source": /this is some pattern/
    }
  },
  { multi: true }
)

这里我想从数组中删除source 中的值与this is some pattern 匹配的所有项目。当我执行这个查询时,它给出了一个错误提示:Cannot use the part (source) of (text.source) to traverse the element with error code 28

实现这一点的方法是什么?

【问题讨论】:

    标签: string mongodb mongoose nosql


    【解决方案1】:

    它给出了一个错误提示:Cannot use the part (source) of (text.source) to traverse the element with error code 28.

    $pull 的更新方法语法不正确,

    更正语法,您可以使用$regex按特定模式查找文档,

    • "text.source" filter部分的条件会过滤主文档,可选
    • text: { source: 将过滤子文档并拉取元素
    db.getCollection('TM').updateMany(
      {
        hostname: "mysite.com",
        "text.source": { $regex: "this is some pattern" }
      },
      {
        $pull: {
          text: { source: { $regex: "this is some pattern" } }
        }
      }
    )
    

    Playground

    【讨论】:

    • 为什么我们需要两次text.source?你能帮我理解一下吗?
    • 查询部分用于过滤主文档,并在更新中从数组元素中过滤并拉取它,如果您未在查询部分中指定它会起作用,但它仍然会在所有文档中搜索没有匹配的字符串。
    • 知道了。它删除了完整的索引权,而不仅仅是源代码部分?
    • 另外,为什么过滤器部分有text.source,拉取部分有text:{source:?它会产生差异吗?
    • 是的,它会删除完整的元素/索引,您可以测试添加更多字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多