MongoDB findOne Example

MongoDB findOne() method returns only one document that satisfies the criteria entered. If the criteria entered matches for more than one document, the method returns only one document according to natural ordering, which reflects the order in which the documents are stored in the database.

MongoDB findOne

MongoDB findOne() syntax is:

db.collection.findOne(<criteria>, <projection>)

criteria – specifies the selection criteria entered.

projection – specifies the list of fields to be displayed in the returned document.

Few important points about MongoDB findOne:

  1. The projection parameter accepts the boolean values of 1 or true , 0 or false. If the projection fields are not specified, all the fields will be retrieved.
  2. MongoDB findOne() always includes the _id field even if not specified explicitly in the projection parameter unless it is excluded.
  3. MongoDB findOne() returns only a document but not a cursor.

MongoDB findOne – Empty Query specification

This operation returns a single document from the collection specified.

For example, db.car.findOne()

Output:

Only one record is retrieved from the car collection. Note that “Polo” was inserted first into the database.

MongoDB findOne – Query specification

This MongoDB findOne operation returns the first matching document from the specified collection along with the selection criteria entered.

For example:

This operation searches for the car named “Zen” or for speed greater than 60 and retrieves the first document satisfying the criteria entered from the car collection.

Projection in MongoDB findOne()

The projection parameter is also applicable for MongoDB findOne method. Let’s look at some scenarios where we can use projection in findOne.

MongoDB findOne – specify the fields to be returned

This operation displays only the fields specified in the query.

For example:

The first document from the Car collection with id, name and color fields are displayed.

MongoDB findOne – return all the fields except the excluded one

This operation retrieves the first document excluding the fields specified in the selection criteria.

For example;

The car name with Volkswagen is retrieved excluding the id, mfdcountry and cno fields.

MongoDB findOne result document

Cursor methods will not work in this operation as the method returns only a single document. In order to print the individual field values from the document, we can use the below code.

This retrieves only the name of the car “Polo”.

MongoDB findOne Java Example

Below is the java program showing different options that we can use with MongoDB findOne().

MongoDBFindOne.java

Output of above program is:

That’s all for MongoDB findOne() method, we will look into more MongoDB options in coming posts.

Reference: Official Doc

By admin

Leave a Reply