Skip to content

Querying & Filtering

Basic Filtering

Equality matches, implicit AND, and how a filter document is actually interpreted.

BeginnerAbout 4 minutes

You already call find and findOne. This module is the filter — the first argument. A filter is just a document. MongoDB keeps a document if every field in the filter matches.

db.users.find({ city: "Bangalore" })

// same meaning
db.users.find({ city: { $eq: "Bangalore" } })
Shorthand equality. This is $eq.
{ name: "Rahul", city: "Bangalore", isActive: true, ... }
{ name: "Priya", city: "Bangalore", isActive: true, ... }

Two keys in one filter are an implicit AND. Both must match. You do not need $and for this.

db.users.find({
  city: "Bangalore",
  role: "developer",
  isActive: true
})
Active developers in Bangalore
SELECT * FROM users
WHERE city = 'Bangalore'
  AND role = 'developer'
  AND isActive = true;
SQL: AND in WHERE. MongoDB: sibling keys.
  • {} matches every document. That is find() with no filter — fine for a tiny collection, a bug in production.
  • A missing field does not equal false or null. { isActive: false } will not return users who have no isActive at all. $exists is two lessons away.
  • Types must match. { age: "28" } does not hit age: 28.

Interview question

How does MongoDB interpret a filter with several fields?

Think about it first.

Practice

Equality filters on the users collection.