I have data in mongoDB as follows
_id : 5d91caf461f93f13e48ac307,
restaurants : [
{
name : 'grace restaurant',
menus : [
{
menu_name : 'chicken soup',
price : 100
},
{
menu_name : 'Biriyani',
price : 250
},
]
},
{
name : 'river side restaurant',
menus : [
{
menu_name : 'veg lollipop',
price : 47
},
{
menu_name : 'Grill chicken',
price : 210
},
]
}
]
Now, I need to update the river side restaurant's menu "Grill chicken's" price to 310.
How can I do that with mongoose or mongoDB function,I have used lot of different functions but no use, Please help me to find this.
Thank you
abdulbari
6,2625 gold badges41 silver badges65 bronze badges
1 Answer 1
We have to use the array filters for the same.
The following is an example:
db.collection.update({},
{
$set:{
"restaurants.$[restaurantFilter].menus.$[menuFilter].price": 310
}
},
{
"arrayFilters":[
{
"restaurantFilter.name":"river side restaurant"
},
{
"menuFilter.menu_name":"Grill chicken"
}
]
})
Before update:
{
"_id" : "5d91caf461f93f13e48ac307",
"restaurants" : [
{
"name" : "grace restaurant",
"menus" : [
{
"menu_name" : "chicken soup",
"price" : 100
},
{
"menu_name" : "Biriyani",
"price" : 250
}
]
},
{
"name" : "river side restaurant",
"menus" : [
{
"menu_name" : "veg lollipop",
"price" : 47
},
{
"menu_name" : "Grill chicken",
"price" : 210
}
]
}
]
}
After update:
{
"_id" : "5d91caf461f93f13e48ac307",
"restaurants" : [
{
"name" : "grace restaurant",
"menus" : [
{
"menu_name" : "chicken soup",
"price" : 100
},
{
"menu_name" : "Biriyani",
"price" : 250
}
]
},
{
"name" : "river side restaurant",
"menus" : [
{
"menu_name" : "veg lollipop",
"price" : 47
},
{
"menu_name" : "Grill chicken",
"price" : 310
}
]
}
]
}
answered Oct 8, 2019 at 12:27
Himanshu Sharma
3,0202 gold badges10 silver badges19 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
abdulbari
Can you please put your response of this query if you tested it?
Himanshu Sharma
@abdulbarik Updated the answer.
Emmanuel R
Thank you very much brother,It's working now...Thanks Alot
Himanshu Sharma
@EmmanuelR Please accept the answer if it seems perfect to you.
lang-js
$operator can update the first array element that matches multiple query criteria specified with the $elemMatch() operator.