MongoDB for Developers with Python Transcripts
Chapter: Working with MongoDB directly from Python: PyMongo
Lecture: Concept: Atomic updates

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Let's review the ideas behind these in place updates. So here we have more or less a complete MongoDB Python program
0:07 using PyMongo here, so we're going to import PyMongo, connect the local database, all the default options,
0:12 and we're going to either create or get access to the bookstore by saying client.bookstore, now we're going to insert an object
0:20 that has no favorited by element, right no list, it just has a title and isbn,
0:25 so after the insert, we're going to end up with an _id and a title and an isbn. And then maybe we want to add this idea of favorited by,
0:35 maybe you want to design this already that way and have an empty list there, but whichever more or less would work the same,
0:42 so we can say I would like to go find the book, the first part of our update statement is the where clause,
0:47 so find by primary key and remember, that's when we call insert_one that's results.inserted_id, so that's going to find the one and only the item
0:56 and then we're going to use the add to set operator and we just pass that as a string in PyMongo, and then we'll push on favorited by such and such.
1:04 We could also use $set to set, say $setTitle: the new book with updated title, or something like this right, so you can use this all over the place
1:15 and what's really cool, now you may be thinking oh this api is kind of crazy, we've got these these dollar operators
1:22 and it's a lot to learn if you're totally new to it, I realize but when we get to MongoEngine, you'll see that
1:27 MongoEngine does this transparently under the cover for us, so you can actually not have to do this,
1:32 you won't have to necessarily remember all of these but you'll get all the benefits that we're describing here.
1:37 If you're using PyMongo, you have to know the api really intimately so we're going to push this 1001 user id on to favorited by
1:43 and maybe we'll push 1002 as well if people signed up at the same time, they saw the same book, they loved it
1:51 and let's go head and push this 1002 again, well not the push operator, but the add to set operator, do this again, because it's add to set
1:57 we're going to get a new document that has new book title, the same isbn and two items and it's favorited by
2:04 and it's going to be 1001 and 1002, because add to set is item potent calling it once or calling it a hundred thousand times,
2:11 it has the same result, other than it might take longer to call it a hundred thousand times, right. So if it's already there it makes no difference
2:17 but if it's not there to push it in super cool operator, really taking advantage of the hierarchical nature of these documents.


Talk Python's Mastodon Michael Kennedy's Mastodon