Reputation: 44091
Suppose I have the following schema
t = {name: 'John', reviews: [{sid: 1, comment: 'Great', rating: 4}, {sid: 2, comment: 'Awesome', rating: 5}]}
db.teacher.save(t)
db.teacher.find()
Now student with sid 2 updates the rating to 4. Are there any in built operations to do this atomically? At the moment I retrieve the entire document, manipulate reviews manually and then $set the entire reviews array. It works but feels a bit heavy handed. I have looked at all of the atomic operators and a lot of them come close but from what I can see none of them quite do what I'm asking. Is there anything that I am missing?
Upvotes: 0
Views: 70
Reputation: 106463
MongoDB, as many other DBMS, implements update command:
db.teacher.update({'reviews.sid': 2}, {$set: {'reviews.$.rating': 4}}, false, true);
As a sidenote, I often recommend this cheatsheet for people who are experienced with SQL, but just have started using Mongo. )
Upvotes: 1
Reputation: 43198
Yes, you can directly update only the key you want using $set and referencing the key using dot notation.
Upvotes: 0