'How to use ArrayFilter with $push to insert sub document
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"
      }         
    }
  ]
})
							
						Solution 1:[1]
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.
References
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
