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" } }){ 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
})SELECT * FROM users
WHERE city = 'Bangalore'
AND role = 'developer'
AND isActive = true;{}matches every document. That isfind()with no filter — fine for a tiny collection, a bug in production.- A missing field does not equal
falseornull.{ isActive: false }will not return users who have noisActiveat all.$existsis two lessons away. - Types must match.
{ age: "28" }does not hitage: 28.
Interview question
How does MongoDB interpret a filter with several fields?
Think about it first.
Every field is ANDed. { city: "Bangalore", isActive: true } means both must match. I only reach for $and when sibling keys cannot express the condition — same field twice, or grouping with $or.
Practice
Equality filters on the users collection.