Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

Assume we have the following collection, which I have few questions about:

"_id" : ObjectId("4faaba123412d654fe83hg876"), 

"user_id" : 123456, "total" : 100, 

"items" : [ 

"item_name" : "my_item_one", 

"price" : 20 

},

"item_name" : "my_item_two", 

"price" : 50 

}, 

"item_name" : "my_item_three", 

"price" : 30 

}

1 - I want to increase the price for "item_name":"my_item_two" and if it doesn't exists, it should be appended to the "items" array.

2 - How can I update two fields at the same time. For example, increase the price for "my_item_three" and at the same time increase the "total" (with the same value).

I prefer to do this on the MongoDB side, otherwise, I have to load the document in client-side (Python) and construct the updated document and replace it with the existing one in MongoDB. 

1 Answer

0 votes
by (106k points)

To update objects in a document's array in MongoDB there is no way to do this in a single query. You have to search the document in the first query:

If document exists use below code:-

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 

{$inc : {"items.$.price" : 1} } , 

false , 

true);

Otherwise,

db.bar.update( {user_id : 123456 } ,

{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } , 

false ,

true);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...