MongoDB Find Documents
To find documents in MongoDB you call find() with a filter document that describes what to match. An empty filter {} matches everything. findOne() returns just the first match, or null when nothing matches.
The examples use the products collection created in the Insert chapter.
find() with an Equality Filter
Match documents where category equals "Snacks".
db.products.find({ category: "Snacks" })[
{ _id: ObjectId('...07'), name: 'Dark Chocolate', category: 'Snacks', price: 4.25, stock: 500 },
{ _id: ObjectId('...09'), name: 'Almonds', category: 'Snacks', price: 15, stock: 60, tags: [ 'organic' ] }
]findOne()
Use findOne when you expect one result, such as looking up by _id.
db.products.findOne({ name: "Honey" }){
_id: ObjectId('6720a5e2c2b9e81d4f3a1b0a'),
name: 'Honey',
category: 'Sweeteners',
price: 11.5,
stock: 0
}Projection: Choosing Fields
The second argument picks which fields to return. 1 includes, 0 excludes. _id is included unless you exclude it.
db.products.find(
{ category: "Beverages" },
{ _id: 0, name: 1, price: 1 }
)[ { name: 'Green Tea', price: 6 }, { name: 'Coffee Beans', price: 22 } ]Querying Arrays and Nested Fields
Matching a value against an array field finds documents whose array contains it. For embedded documents use dot notation in quotes.
db.products.find({ tags: "organic" }, { _id: 0, name: 1 })
db.customers.find({ "address.city": "Karachi" }, { _id: 0, name: 1 })[ { name: 'Basmati Rice' }, { name: 'Almonds' } ]
[ { name: 'Sara Khan' } ]Counting Results
countDocuments counts matches for a filter.
db.products.countDocuments({ category: "Beverages" })2
Frequently asked questions
How do I find a document by _id in MongoDB?
Wrap the id string in ObjectId: db.products.findOne({ _id: ObjectId("6720a5e2c2b9e81d4f3a1b0a") }). Comparing to a plain string will not match.
What does find() return?
find() returns a cursor, not an array. mongosh prints the first 20 results; type "it" for more. In drivers call toArray() or iterate the cursor.
Can I mix inclusion and exclusion in a projection?
No, except for _id. A projection is either a list of fields to include or a list to exclude.