Selecting all the documents
In this example, we are selecting all the documents of the contributor collection and displaying on the screen using db.collection.find() method.
Syntax:
db.contributor.find()
MongoDB – Query Documents using Mongo Shell
MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document.
find() is a mongo shell method, which can be used in the multi-document transactions. The documents displayed by this method are in non-structured form. If you want to get data in a structured form, then use pretty() method with find() method.
db.collection.find().pretty()
This method iterates the cursor automatically to display the first 20 documents of the collection. If you want this method will display more than 20 documents, then type it to continue the iteration.
Syntax:
db.collection.find(filter, projection)Parameters:
- filter: It is an optional parameter. It specifies the selection filter with the help of query operators. And if you want to get all the documents present in the collection, then omit these parameters or pass an empty document in the method. The type of this parameter is a Document.
- projection: It is an optional parameter. It specifies that only those fields return to the document that matches the given query filter. And if you want to get all the fields in the document, then omit this parameter.
Return: This method returns a cursor to the documents that match the specified query criteria. When you use find() method, it returns documents which means the method is actually returning the cursor to the documents.
Examples:
In the following examples, we are working with:
Database: w3wiki Collection: contributor Document: five documents that contain the details of the contributors in the form of field-value pairs.