Home > OS >  How to use ArrayFilter with $push to insert sub document
How to use ArrayFilter with $push to insert sub document

Time:10-19

We have a requirement to insert to the sub array when sub array contains some value, but I get an error when using push with arrayFilter: fail to run update: write exception: write errors: [The field 'subArr.0' must be an array but is of type object in document {_id: "1"}]

You can reproduce it using the playground.

db.collection.update({},
{
  $push: {
    "subArr.$[a0]": {
      "input1": "c",
      "title": "s3"
    }
  }
},
{
  arrayFilters: [
    {
      "a0.title": {
        "$eq": "s1"
      }         
    }
  ]
})

CodePudding user response:

For your scenario, arrayFilters is not suitable.

It is used to retrieve specific element(s) that match the condition (in arrayFilter) for to-be-updated element(s).

You are trying to $push object to the filtered subArr's item which is not an array.

Instead, you have to filter the document for collection and next update the document as below:

db.collection.update({
  "subArr.title": {
    $eq: "s1"
  }
},
{
  $push: {
    "subArr": {
      "input1": "c",
      "title": "s3"
    }
  }
},
// For update multiple documents
{
  multi: true 
})

Note: If you need to update for multiple documents, then requires to add

{ multi: true }

in your query.

Sample Mongo Playground


References

How the arrayFilters Parameter Works in MongoDB

  • Related