MongoDB - FindOne Query

MongoDB allows us to retrieve a single record with the findOne() method. This function returns one document that matches the query specifications. If multiple documents match the query, the first document from the natural order will be returned. If the method does not find a match, it returns null.

connecting to test  
> db.people.findOne();
  '_id' : ObjectId('561e...'),
  'name' : 'Craig Derington',
  'address' : {
      'street' : '1234 Main Street',
      'city' : 'New York City',
      'state' : 'NY',
      'zip_code' : '10021'
  'role' : 'admin',
  'is_active' : True,
  'last_login' : '09-12-2015T13:13:55',
  'date_of_birth' : '08-22-1990'

It should be noted that the findOne() method only has the following parameters.

Query selection criteria using query operators.

Explicit definition of the fields to return using the projection operator. Omit this to return all fields.

So, let's try a query in the people collection where either the name field in the embedded document starts with a c or where the date of birth is less than the new date created.

connecting to: test  
> db.people.findOne(
      $or : [
        { 'name' : /^C/ },
        { 'date_of_birth' : { $lt : new Date('01/01/2005')}}

Using a query like this with projection allows us to specify the fields in which we want MongoDB to return. The parameters must either explicitly include or exclude fields, but not both, unless the excluded field is for the id field.

Return all fields but the excluded. In this query, we want to find all admins, but exclude their names, ids and date of births.

connecting to: test  
> db.people.findOne(
  { 'role' : 'admin'},
  { 'id' : 0, 'name' : 0, 'date_of_birth' : 0}

Next, we'll take a look at the count() method...

Craig Derington

Secular Humanist, Libertarian, FOSS Evangelist building Cloud Apps developed on Red Hat Enterprise Linux and Ubuntu Server. My toolset includes Python, Celery, Flask, Django, MySQL, MongoDB and Git.

comments powered by Disqus