MongoDB for Developers with Python Transcripts
Chapter: MongoDB's shell and native query syntax
Lecture: Exact subdocument matches

Login or purchase this course to watch this video and the rest of the course contents.
0:01 So here's an interesting question— what if I want to find all the books
0:03 where user 720 has rated that book exactly a nine.
0:09 You would think that this would do it, right,
0:11 we're using both values in this prototypical object or this document here
0:15 and it says that the book is going to have to have
0:18 a rating of nine and user id 720 has rated it.
0:21 However, when we run this, you'll see we get mixed results.
0:24 The bottom one looks perfect, we got a book with the user id 720
0:29 an a value of nine in the ratings, great;
0:32 but this other one, what's up with this, the red one?
0:34 Well, user 601 rated this as a nine,
0:38 and user 720 actually hated the book, they gave it a one.
0:41 However, taken as a whole, does the book have a rating by user id 720— yes,
0:46 does it have a rating of nine— yes, so it matches this and clause.
0:49 So, oftentimes if you're looking for this exact subdocument match
0:54 and that thing you're looking in is an array
0:56 so ratings is an array of documents, if ratings was one subdocument,
1:00 this would work fine, but if it's an array and you want to say
1:04 I need to make sure that the thing in that array is
1:07 that subdocument itself matches value and user id as I've specified here
1:11 you need a different query operator, and that is dollar element match;
1:15 so you can run this and it'll look down inside and say
1:18 I want to find all the things in ratings,
1:21 where both, the user id is 720 and the value is nine.
1:25 So this is a slightly more complex version
1:27 that you have to run and you have to use
1:29 because you run into that problem we had before
1:31 where somebody voted a 9, user 720 voted,
1:33 but it was not user 720 who voted nine.
1:35 So a little bit different than if you were working in
1:38 say a sequel traditional tabular language
1:41 because you don't ever have this kind of duplication within the one result,
1:45 so it would be a lot simpler, but this is something
1:48 that you kind of got to get your head around a little bit,
1:50 you luckily don't use it very often, and if you are using the higher level of things
1:54 like MongoEngine, you won't run into it,
1:56 but down here at the shell or in PyMongo,
1:58 you have to be really careful if this is actually
2:00 the question you're trying to ask and answer.