Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)

The syntax is { field: { $op: value } } where $op is any comparison operator:

  • $lt, $lte: less than, less than or equal
  • $gt, $gte: greater than, greater than or equal
  • $in: member of. value must be an array of values
  • $ne, $nin: not equal, not a member of
  • $exists: checks whether the document posses the property field. value should be true or false
  • $regex: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of $options with $regex is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the $regex operator when you need to use another operator with it (see example below)
  1. // $lt, $lte, $gt and $gte work on numbers and strings
  2. db.find({ "humans.genders": { $gt: 5 } }, function (err, docs) {
  3. // docs contains Omicron Persei 8, whose humans have more than 5 genders (7).
  4. });
  5. // When used with strings, lexicographical order is used
  6. db.find({ planet: { $gt: 'Mercury' }}, function (err, docs) {
  7. // docs contains Omicron Persei 8
  8. })
  9. // Using $in. $nin is used in the same way
  10. db.find({ planet: { $in: ['Earth', 'Jupiter'] }}, function (err, docs) {
  11. // docs contains Earth and Jupiter
  12. });
  13. // Using $exists
  14. db.find({ satellites: { $exists: true } }, function (err, docs) {
  15. // docs contains only Mars
  16. });
  17. // Using $regex with another operator
  18. db.find({ planet: { $regex: /ar/, $nin: ['Jupiter', 'Earth'] } }, function (err, docs) {
  19. // docs only contains Mars because Earth was excluded from the match by $nin
  20. });