Deleting items from the array of objects

Viewed 34

I have a document that looks like:

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

and I am trying to delete the items from the text array which match a specific condition in my query given as:

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

Here I want to delete all the items from the array where the value inside source matches this is some pattern. When I execute this query, it gives an error saying: Cannot use the part (source) of (text.source) to traverse the element with error code 28.

What is the way to achieve this?

1 Answers

it gives an error saying: Cannot use the part (source) of (text.source) to traverse the element with error code 28.

Incorrect syntax of $pull for update methods,

Corrected syntax, and You can use $regex to find document by specific pattern,

  • "text.source" the condition in filter part will filter main documents, it is optional
  • text: { source: will filter sub documents and pull elements
db.getCollection('TM').updateMany(
  {
    hostname: "mysite.com",
    "text.source": { $regex: "this is some pattern" }
  },
  {
    $pull: {
      text: { source: { $regex: "this is some pattern" } }
    }
  }
)

Playground

Related