Skip to content
Related Articles

Related Articles

MongoDB – db.collection.Find() Method
  • Last Updated : 17 Feb, 2021

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one. If we want to return pointer on all documents then use empty() parameter that returns all documents one by one. It takes only some optional parameters. The first optional parameter is the selection criteria on which we want to return a cursor. To return all documents in a collection use empty document({}). Using this method you can also replace embedded documents. You can also use this method in multi-document transactions. If you use this method in the mongo shell, then the shell will automatically iterate the cursor to display up to 20 documents in the collection, if you want to continue then type it or you can manually iterate the result of the find() method by assigning the returned cursor to a variable with the var keyword. You can also modify the behavior of this method using cursor methods.

Syntax:

db.Collection_name.find(selection_criteria, projection)

Optional parameters:

  • selection_criteria: It specifies selection criteria. To return all documents in a collection use empty document({}). The type of this parameter is document.
  • projection: It specifies the fields to return in the documents that match the selection criteria. To return all fields in the matching documents, remove this parameter. It is of the document type.

This document takes:



{ field1: <value1>, field2: <value2> ... }

Here if the value of the field is 1/true then it specifies the inclusion of the field, or if the value of the field is 0/false then it specifies the exclusion of the field.

Return:

It returns a cursor to the documents that match the selection criteria. When the find() method returns documents, the method is actually returning a cursor to the documents.

Examples:

In the following example, we are working with:

Database: gfg

Collections: student

Document: Three documents contains the details of the students

  • Find all the documents present in the collection:
db.student.find()

  • Find all the documents present in the collection by passing empty document:
db.student.find({})

  • Find all the document that matches the given filter query(i.e., age:18):
db.student.find({age:18})

  • Find the embedded document that matches the given filter query:
db.student.find({score:{math: 230, science: 234}})

  • Display only the specified fields(Using Projection):
db.student.find({},{name:1, _id:0})

  • Display only two documents using the limit() method:
db.student.find().limit(2)

My Personal Notes arrow_drop_up
Recommended Articles
Page :