TExcelTAD
Home › MongoDB › MongoDB Find

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:

mongosh · try it yourself
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:

mongosh · try it yourself
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:

mongosh · try it yourself
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:

mongosh · try it yourself
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 an address that 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:

mongosh · try it yourself
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

mongosh · try it yourself
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?

  1. An empty cursor
  2. null
  3. {}
  4. It throws an error

Which filter finds customers living in Boston?

  1. { address: 'Boston' }
  2. { 'address.city': 'Boston' }
  3. { address: { city: 'Boston' } }
  4. { city: 'Boston' }

tags is ['dark', 'ground', 'decaf']. Does { tags: 'decaf' } match?

  1. No, the whole array must equal 'decaf'
  2. Yes, an element equals 'decaf'
  3. Only with $in
  4. Only if 'decaf' is first