Introduction to MongoDB collection.findOne() Method

The findOne() method is a query method in MongoDB database used to query a single document in a collection that matches the specified criteria and return that document. If multiple documents need to be returned, the find() method should be used instead.

Syntax

The syntax of the findOne() method is as follows:

db.collection.findOne(query, projection)

The query parameter is a document that specifies the query criteria, and the projection parameter is a document that specifies the fields to be returned, and can be omitted.

Use Cases

The findOne() method is suitable for scenarios that require querying a single document, such as querying information for a specific user or querying the latest log record.

Examples

Assume there is a users collection that contains user information, including fields such as name, age, gender, and address. To query the information of a user who is 25 years old, the following command can be used:

db.users.findOne({ age: 25 })

Assume there is also a logs collection that contains log information, including fields such as time, user, action, and result. To query the information of the latest log record, the following command can be used:

db.logs.findOne({}, { sort: { time: -1 } })

In this example, the first empty object {} represents an empty query condition, i.e., all documents in the collection are returned. The sort parameter is used to specify the descending order of the time field, so that the latest document is ranked first. Since no fields to be returned are specified, all fields in the collection are returned by default.

Conclusion

The findOne() method can query a single document that matches the specified criteria and return that document. When using it, query criteria and fields to be returned need to be specified. It is suitable for scenarios that require querying a single document.