MongoDB - Find Queries

This is the simplest of the MongoDB queries. A simple find operation.

connecting to test  
> db.people.find().pretty();
{
  '_id' : ObjectId('5561e...')
  'name' : 'Craig Derington',
  'address' : {
      'street' : '1234 Main Street',
      'city' : 'Coos Bay',
      'state' : 'OR',
      'zip_code' : '97402'
  },
  'profession' : 'Developer',
  'email' : 'craig@craigderington.me',
  'phone_number' : '541-555-1212',
  'is_active' : True,
}
Type "it" for more  

The expression we typed into the shell, broken apart to show each part of the query.

db = the start of the command  
people = the collection in which to search  
find() = the operation to perform, with no operators  
pretty() = make the output readable  

Our queries can get much more complex with larger collections.

Let's imagine we had a collection with millions of records. We would never want to run a find() query, because that would be a waste of resources.

Instead, we need to pass operators to the find clause.

connecting to: test  
> db.people.find({ 'name' : { $regex : 'je' }, 'email' : { $exists : true }})
{
  '_id' : ObjectId('5561e...')
  'name' : 'Jeff Wilson',
  'address' : {
      'street' : '444 S. Broadway',
      'city' : 'Portland',
      'state' : 'OR',
      'zip_code' : '97201'
  },
  'profession' : 'Engineer',
  'email' : 'craig@craigderington.me',
  'phone_number' : '503-444-1312',
  'is_active' : True,
}

Here is a link to a decent cheat sheet for MongoDB queries. Link

SQL to Mongo DB query translator Link

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus