Mongoose - How to push object in nested array of objects

  1. Use arrayFilters to filter the nested document(s) in the array field, then $push if the filter criteria in the arrayFilters met.
db.collection.update({
  "_id": _id,
  "menu.dishCategory": dishCategoryId
},
{
  $push: {
    "menu.$[menu].dishMeals": newDish
  }
},
{
  arrayFilters: [
    {
      "menu.dishCategory": dishCategoryId
    }
  ]
})

Sample Mongo Playground


You can do it with arrayFilters config in update query:

db.collection.update({
  "restaurant_id": 1
},
{
  "$push": {
    "menu.$[element].dishMeals": {
      "dishMealName": "Best Burger",
      "dishMealIngredients": "Best burger in town",
      "dishMealPrice": 10
    }
  }
},
{
  "arrayFilters": [
    {
      "element.dishCategory._id": "61e6089f209b802518e2b4a4"
    }
  ]
})

Working example


You may read the question and the solution they provided here, Hope this one will be helpful to you.

db.collection.update({
    "_id": 1,
    "menu.dishCategory": "61e6089f209b802518e2b4a4"
},
{
    $push: {
        "menu.$.dishMeals": newMeal
    }
})