Querying Documents
find() and findOne() read documents back out, and a small set of query operators like $gt, $in, and $or handle everything WHERE does in SQL.
Finding everything, and finding one
JS mongosh
db.posts.find()
Output
[
{ _id: ObjectId("65f1a3104c1a2b3c4d5e6f71"), title: 'Hello, MongoDB', author: 'Priya', views: 0 },
{ _id: ObjectId("65f1a3334c1a2b3c4d5e6f72"), title: 'Indexes Explained', author: 'Sam', views: 12 },
{ _id: ObjectId("65f1a3334c1a2b3c4d5e6f73"), title: 'Schema Design 101', author: 'Priya', views: 5 }
]A query filter — a document describing what to match — narrows that down. findOne() works the same way but only ever returns a single document:
JS mongosh
db.posts.findOne({ author: "Priya" })
Output
{ _id: ObjectId("65f1a3104c1a2b3c4d5e6f71"), title: 'Hello, MongoDB', author: 'Priya', views: 0 }Comparison operators
Operators like $gt (greater than) and $in (matches any value in a list) go inside the filter, keyed to the field they apply to:
JS mongosh
db.posts.find({ views: { $gt: 4 } })
Output
[
{ _id: ObjectId("65f1a3334c1a2b3c4d5e6f72"), title: 'Indexes Explained', author: 'Sam', views: 12 },
{ _id: ObjectId("65f1a3334c1a2b3c4d5e6f73"), title: 'Schema Design 101', author: 'Priya', views: 5 }
]JS mongosh
db.posts.find({ author: { $in: ["Priya", "Sam"] } })
Output
// matches all three documents — every author is either Priya or Sam
$or and projections
$or takes an array of filters and matches a document that satisfies any of them. A second argument to find() — a projection — controls which fields come back:
JS mongosh
db.posts.find(
{ $or: [{ views: 0 }, { author: "Sam" }] },
{ title: 1, _id: 0 }
)
Output
[
{ title: 'Hello, MongoDB' },
{ title: 'Indexes Explained' }
]The $eq/null gotcha: querying
{ field: null } matches documents where field is explicitly set to null and documents where field doesn't exist at all — both count. If you specifically need "this field is present but null," you need { field: { $type: "null" } }, or check for presence separately with $exists.