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