English subtitles

← Regex Operator - Data Wranging with MongoDB

Get Embed Code
4 Languages

Showing Revision 2 created 05/25/2016 by Udacity Robot.

  1. Earlier we looked at querying string valued fields using
  2. the greater than and less than operators. Returning to
  3. our consideration of queries matching string fields. There are
  4. more complicated sorts of queries that you might want to
  5. perform on strings than just equality and inequality. For
  6. example, we often want to look for patterns in
  7. strings. MongoDB supports querying for string patterns using the
  8. regex operator. Regex is based on a regular expression library.
  9. In particular, the Perl Compatible Regular Expressions library.
  10. For more information, I'd encourage you to just Google
  11. for this. So the regex operator allows us
  12. to do regular expression queries in MongoDB. Let's look
  13. at some examples. Now in this collection, city
  14. documents, contain a motto field or at least some
  15. of them do. So as an example of
  16. doing regex queries in MongoDB, let's take a look
  17. at some of the words these mottos contain. This
  18. is a very simple regular expression. In fact, we
  19. don't even need regex to do this one. So
  20. if I do the query this way, I should match
  21. only documents where friendship is the entire string of
  22. the motto. And here we go, friendship. Okay, so now
  23. let's begin to expand this regular expression. What I'm
  24. going to do first is introduce a very simple change.
  25. Now we're looking for all mottos that contain
  26. the word friendship. And friendship can either be capitalized
  27. or not. And so here we have four, where
  28. before we have simply one document. Okay so, now
  29. let's expand this a little bit more. And if
  30. your regex skills are a little rusty, please see
  31. the instructor notes for documentation and pointers to some
  32. tutorials. So let's expand this to include another word.
  33. Okay, so this regular expression will identify all documents
  34. containing a motto with either the word friendship or the
  35. word pride. And either word can be capitalized. Let's
  36. take a look at the actual models themselves. And again,
  37. I'm going to use a projection to make it
  38. a little bit easier to see the mottos. Okay and
  39. we can see that each one of these has
  40. either the word pride or the word friendship in it.
  41. And capitalization doesn't matter. Okay so, that's about all the farther I
  42. want to go with regex queries in this example. The point here is
  43. that MongoDB supports Perl Compatible Regular Expressions. So, you have a lot of
  44. power in what types of queries you can do involving string value fields.