1

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
asked Oct 8, 2019 at 12:17
1
  • 1
    May be this docs.mongodb.com/manual/reference/operator/update/positional in the part of "Update Embedded Documents Using Multiple Field Matches" can help you to find the way The $ operator can update the first array element that matches multiple query criteria specified with the $elemMatch() operator. Commented Oct 8, 2019 at 12:36

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Can you please put your response of this query if you tested it?
@abdulbarik Updated the answer.
Thank you very much brother,It's working now...Thanks Alot
@EmmanuelR Please accept the answer if it seems perfect to you.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.