- Reference >
mongoShell Methods >- Collection Methods >
- db.collection.findOne()
db.collection.findOne()¶
On this page
Definition¶
-
db.collection.findOne(<criteria>, <projection>)¶ Returns one document that satisfies the specified query criteria. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. In capped collections, natural order is the same as insertion order. If no document satisfies the query, the method returns null.
Parameter Type Description criteriadocument Optional. Specifies query selection criteria using query operators. projectiondocument Optional. Specifies the fields to return using projection operators. Omit this parameter to return all fields in the matching document.
The projection parameter takes a document of the following form:
The <boolean> can be one of the following include or exclude values:
1ortrueto include. ThefindOne()method always includes the _id field even if the field is not explicitly specified in the projection parameter.0orfalseto exclude.
The projection argument cannot mix include and exclude
specifications, with the exception of excluding the _id field.
returns: One document that satisfies the criteria specified as the first argument to this method. If you specify a
projectionparameter,findOne()returns a document that only contains theprojectionfields. The_idfield is always included unless you explicitly exclude it.Although similar to the
find()method, thefindOne()method returns a document rather than a cursor.
Examples¶
With Empty Query Specification¶
The following operation returns a single document from the bios collection:
With a Query Specification¶
The following operation returns the first matching document from the
bios collection where either
the field first in the subdocument name starts with the letter
G or where the field birth is less than new
Date('01/01/1945'):
With a Projection¶
The projection parameter specifies which fields to return. The
parameter contains either include or exclude specifications, not both,
unless the exclude is for the _id field.
Specify the Fields to Return¶
The following operation finds a document in the bios collection and returns only the name,
contribs and _id fields:
Return All but the Excluded Fields¶
The following operation returns a document in the bios collection where the contribs field
contains the element OOP and returns all fields except the _id
field, the first field in the name subdocument, and the
birth field: