find() — ask questions with a document
The query itself is a document: { field: value } means "match documents where that
field equals that value." A second argument, the projection, chooses which fields
come back. That's 90% of everyday MongoDB reading.
db.customers.find({ vip: true, city: "Cairo" }) reads as:
"In the customers collection, go through the documents one by one, and give me every
document that looks like this example — vip is true AND city is Cairo."
That's the mental model: the thing inside find(…) is not code, it's a mini example
document to match against. Open 📂 Meet your data above and check by eye which customers
should survive — then run it and confirm.
List every key you want to match. Multiple keys mean all must match (an implicit AND):
The second argument to find() is a projection. 1 = include, 0 =
exclude. _id shows up unless you turn it off with _id: 0. Toggle the fields and
watch the output shrink:
{ name: 1, price: 1 }) or an
exclude list ({ tags: 0 }). The only field you can always flip independently is
_id.
MongoDB is smart about arrays. { tags: 'milk' } matches any product whose
tags array contains 'milk' — you don't write any special "contains"
operator. Pick a tag and see:
findOnefind() returns all matches; findOne() returns just the first (or
null). Combine with a dotted path to reach into sub-documents:
db.products.find({ category: "Tea", price: 3.5 }) returns documents where…{ name: 1, _id: 0 } do?name, and explicitly drop the default _id. The result
documents have just one field.{ tags: "hot" } on a document whose tags is ["hot","milk"]…