MongoDB for Developers with Python Transcripts
Chapter: MongoDB's shell and native query syntax
Lecture: Updating documents in MongoDB

Login or purchase this course to watch this video and the rest of the course contents.
0:01 If inserts are simple, updates maybe not so much. In fact, there are two types of updates that we're going to look at;
0:07 first, we're going to look at what is the conceptually more simple one, but also slightly more problematic.
0:12 So I'm going to call this the whole document update and the way you might use this is you might go to the database,
0:18 do a query, get a document back, make a change to it and say here, push this whole document
0:23 back over top the existing one in the database, kind of orm style. The other one that we're not talking about here would be the in place updates,
0:32 so you might say go increment the view count of this post without retrieving it, without changing the other parts,
0:39 ok, so how does the whole document update work? Well, first of all, we're going to do an update
0:44 if we come back and we look at it, we'll see maybe we've changed the title here, the author is still the same, but we had to pass the author,
0:49 we had to pass the published and the isbn back, okay, in fact also the id, so all that stuff we had to put back,
0:56 basically the way it works is we're going to do a where clause here so find it by the primary key, this great long object id
1:03 and then here is the entire whole document we want to replace that document with. Now because of the way it's working here,
1:10 there's a couple of features or settings you might want to control here, so you might need to set these, you might not depending on what you're doing,
1:17 the default is if the where clause does not match, nothing will happen, there will be no kind of upsert, there will not be a new document added
1:25 because we didn't find one, just nothing happens. So if you say upsert is true and you run this update,
1:30 it will say I didn't find this document, so let me create it for you, so you could control that here.
1:35 Similarly with multi equal true, normally unlike sql statements update only updates the first item it finds
1:41 even if the where clause would match ten things, it only updates one of them.
1:44 So that's a little bit funky, but if you think it's entirely replacing the record like why would that hole record be duplicated ten times,
1:52 I don't know, it's kind of weird, but if you do want to update multiple objects, multiple documents in this collection, be sure to set multi to true,
1:58 both of those orange values, their default values are false.

Talk Python's Mastodon Michael Kennedy's Mastodon