Logical operators $or, $and, $not, $where

You can combine queries using logical operators:

  • For $or and $and, the syntax is { $op: [query1, query2, …] }.
  • For $not, the syntax is { $not: query }
  • For $where, the syntax is { $where: function () { / object is "this", return a boolean / } }
  1. db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }] }, function (err, docs) {
  2. // docs contains Earth and Mars
  3. });
  4. db.find({ $not: { planet: 'Earth' } }, function (err, docs) {
  5. // docs contains Mars, Jupiter, Omicron Persei 8
  6. });
  7. db.find({ $where: function () { return Object.keys(this) > 6; } }, function (err, docs) {
  8. // docs with more than 6 properties
  9. });
  10. // You can mix normal queries, comparison queries and logical operators
  11. db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }], inhabited: true }, function (err, docs) {
  12. // docs contains Earth
  13. });