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 where user 720 has rated that book exactly a nine.
0:10 You would think that this would do it, right, we're using both values in this prototypical object or this document here
0:16 and it says that the book is going to have to have a rating of nine and user id 720 has rated it.
0:22 However, when we run this, you'll see we get mixed results. The bottom one looks perfect, we got a book with the user id 720
0:30 an a value of nine in the ratings, great; but this other one, what's up with this, the red one? Well, user 601 rated this as a nine,
0:39 and user 720 actually hated the book, they gave it a one. However, taken as a whole, does the book have a rating by user id 720— yes,
0:47 does it have a rating of nine— yes, so it matches this and clause. So, oftentimes if you're looking for this exact subdocument match
0:55 and that thing you're looking in is an array so ratings is an array of documents, if ratings was one subdocument,
1:01 this would work fine, but if it's an array and you want to say I need to make sure that the thing in that array is
1:08 that subdocument itself matches value and user id as I've specified here you need a different query operator, and that is dollar element match;
1:16 so you can run this and it'll look down inside and say I want to find all the things in ratings, where both, the user id is 720 and the value is nine.
1:26 So this is a slightly more complex version that you have to run and you have to use because you run into that problem we had before
1:32 where somebody voted a 9, user 720 voted, but it was not user 720 who voted nine. So a little bit different than if you were working in
1:39 say a sequel traditional tabular language because you don't ever have this kind of duplication within the one result,
1:46 so it would be a lot simpler, but this is something that you kind of got to get your head around a little bit,
1:51 you luckily don't use it very often, and if you are using the higher level of things like MongoEngine, you won't run into it,
1:57 but down here at the shell or in PyMongo, you have to be really careful if this is actually the question you're trying to ask and answer.

Talk Python's Mastodon Michael Kennedy's Mastodon