3

I have this data structure in my MongoDB database:

"menu": [
        {
            "dishCategory":"61e6089f209b802518e2b4a4",
            "dishMeals": [
                {
                    "dishMealName": "Burger King",
                    "dishMealIngredients": "Burger lepinja, bbq sos, berlin sos, zelena"
                    "dishMealPrice": 5
                }
            ]
        }
    ]

How do I push a new object inside dishMeals in exact dishCategory ( I am providing dishCategoryId, newDish object and _id of restaurant through req.body) I've tried this but nothing is changing:

await Restaurants.updateOne(
        {
            '_id' : _id,
            'menu.dishCategory' : dishCategoryId
        },
        {
            $push : {
                'menu.$.dishMeals' : newDish
            }
        }
    );
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
mne_web_dev
  • 261
  • 4
  • 12

3 Answers3

4
  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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • Sorry I've made a mistake I have "dishCategory":"61e6089f209b802518e2b4a4" not the object one like earlier. When I try like this "menu.dishCategory": dishCategoryId" Its not working – mne_web_dev Jan 20 '22 at 00:58
  • 1
    [Demo](https://mongoplayground.net/p/GMdbyyhtvdz) looks fine for me. Maybe another thing to look up is make sure you pass the value with exact type, for example, if `dishCategory` is ObjectId, then the value of `dishCategoryId` must also be ObjectId type as well. – Yong Shun Jan 20 '22 at 01:02
2

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

NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • Thank you your method is working fine it was my mistake for not checking if dishCategory is indeed an ObjectId not a string – mne_web_dev Jan 20 '22 at 18:28
2

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
    }
})

Sample Example

kumol
  • 174
  • 1
  • 9
  • Thank you your method is working fine it was my mistake for not checking if dishCategory is indeed an ObjectId not a string – mne_web_dev Jan 20 '22 at 18:28