Open In App

MongoDB – FindOne() Method

The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk. If no document matches the selection criteria, then this method will return null. It takes two parameters first one is the query criteria and the other is optional.

“field.nestedfieldname”: <value>



or

{field: {nestedfieldname: <value>}}



Syntax:

db.Collection_Name.findOne(

    query:<document>,

    projection:<document>

)

Parameters:

Optional parameters:

projection: The projection parameter determines which fields are returned to the matching documents. The projection parameter takes a document that contains field : value pairs:

{field1: <value1>, field: <value2>…}

Here,

Return:

It returns one matched document with the specified query criteria in the collection. And if you specify a projection parameter, then is method returns a document that only contains projection fields.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains name and the language in which they are interested.

db.student.findOne()

db.student.findOne({language:"python"})

db.student.findOne({language:"c++"})

db.student.findOne({name: "Avinash"}, {_id: 0, language:1})

Here, we find a document whose name is “Avinash”, and only want to display the language that Avinash know. So, in the projection document, we set the value of the language field to 1 and the value of _id to 0.

Article Tags :