MongoDB Find
Reading data is done with find() and findOne():
| Method | Returns |
|---|---|
find(filter, projection) |
a cursor over every matching document |
findOne(filter, projection) |
the first matching document, or null |
countDocuments(filter) |
the number of matches |
distinct(field, filter) |
the distinct values of one field |
Find all documents
An empty filter matches everything. Here we print just the names of all customers:
print(db.customers.find().toArray().map(c => c.name));[
'Ada Lovelace',
'Alan Turing',
'Grace Hopper',
'Linus Torvalds',
'Margaret Hamilton',
'Tim Berners-Lee',
'Barbara Liskov',
'Donald Knuth',
'Hedy Lamarr',
'Katherine Johnson',
'Edsger Dijkstra',
'Radia Perlman'
]
Equality filters
A filter field with a plain value matches documents where the field equals that value. Several fields in one filter are combined with AND:
print(db.customers.find({ tier: 'gold' }).toArray().map(c => c.name));
print(db.products.find({ category: 'tea', stock: 0 }).toArray().map(p => p.name));[ 'Ada Lovelace', 'Grace Hopper', 'Barbara Liskov' ]
[ 'Chamomile Calm' ]
findOne
findOne returns a document instead of a cursor, so no .toArray() is needed. If nothing matches it returns null, so check before using the result:
const order = db.orders.findOne({ customerId: 9 });
print(order._id, order.status, order.total);
const missing = db.orders.findOne({ customerId: 4 });
print(missing);
if (!missing) print('Customer 4 has no orders yet.');1009 delivered 37
null
Customer 4 has no orders yet.
When several documents match, "first" means the first in the collection's natural order unless you sort. To say which one you want, use find(...).sort(...).limit(1).
Nested fields: dot notation
To filter on a field inside an embedded document, join the path with dots and quote it:
db.customers.find({ 'address.country': 'UK' }).forEach(c => print(c.name, '-', c.address.city));
print(db.products.find({ 'specs.material': 'steel' }).toArray().map(p => p.name));Ada Lovelace - London
Alan Turing - Manchester
[ 'Burr Grinder', 'Gooseneck Kettle' ]
Warning:
{ address: { city: 'London' } }is not the same as{ 'address.city': 'London' }. The first asks for anaddressthat is exactly{ city: 'London' }, with no other fields, so it matches nobody here.
Matching values inside arrays
When a field holds an array, an equality filter matches if any element equals the value:
print(db.products.find({ tags: 'vegan' }).toArray().map(p => p.name));
print(db.orders.find({ 'items.productId': 12 }).toArray().map(o => o._id));[ 'Dark Chocolate Bar', 'Oat Cookies' ]
[ 1004, 1015 ]
The second line reaches through the items array into each embedded line item: it finds every order containing product 12. You will learn more array queries in Querying Arrays.
Counting and distinct values
print(db.orders.countDocuments({ status: 'processing' }));
print(db.customers.distinct('address.country'));
print(db.orders.distinct('customerId', { status: 'cancelled' }));5
[ 'Austria', 'Netherlands', 'Switzerland', 'UK', 'USA' ]
[ 6, 7 ]
distinct returns sorted unique values and also looks inside arrays.
Test yourself
What does findOne() return when no document matches?
- An empty cursor
null{}- It throws an error
Which filter finds customers living in Boston?
{ address: 'Boston' }{ 'address.city': 'Boston' }{ address: { city: 'Boston' } }{ city: 'Boston' }
tags is ['dark', 'ground', 'decaf']. Does { tags: 'decaf' } match?
- No, the whole array must equal 'decaf'
- Yes, an element equals 'decaf'
- Only with $in
- Only if 'decaf' is first