MongoDB find
Overview
MongoDB Find() is a method used to query data from a collection. It takes a query object as a parameter and returns all documents that match the query. The query object contains one or more key-value pairs, with each pair representing a condition that the documents must meet to be returned by the query. MongoDB find() method is thus one of the most commonly used methods for retrieving data from a collection. Using the find() method, we can either retrieve all data in the collection or retrieve data based on certain criteria by combining it with other methods to perform more complex queries.
Basics of MongoDB Find()
MongoDB find() method is used to perform a query on a collection and the method returns a cursor to matched documents. To use MongoDB find(), we first need to select the collection we want to query using the 'db.collection' notation and then call the find() method. Hence the syntax looks like this:
To understand how we use MongoDB Find() method, let us consider we have a database called BooksDB and a collection named BookList which has a list of books along with author name and various other parameters. So if we want to view all the documents in the collection then the query will look like this:
This will give you the entire list of documents in the collection.
Let's connect to our mongoshell and see the results:
To connect to mongoshell, open your command prompt and type mongosh and then select the database you want to use. To select a database use the use keyword followed by the db name.
Use the show keyword command to list the available database.
To create a new db, there is no special keyword in MongoDB to create a db. By selecting the database, its creation is taken care of by Mongodb on the first write command.
Please run this command to populate the db. This will help you to keep up with the tutorials.
Now let's test the find method.
To perform specific queries, we use different other methods within MongoDB Find() method using the syntax as
db.collectionName.find({field: value})
By this command, it implies that find documents in the collection that matches the condition. Suppose we want all books from our collection where the author's name is James Clear. We will then use a command like:
The projection object can be used to limit the fields that are returned in the result set. You can specify which fields to include or exclude using the projection object:
This will return only the field1 and field2 fields for all documents in the collection. Suppose we want a book by the name 'Evil Under The Sun' and the author name is 'Agatha Christie'. Our command should then be :
In a nutshell, the syntax for MongoDB find() becomes:
db.collectionName.find(query, projection, options)
Let's understand what each of these means:
-
Query: The query parameter allows you to filter the documents that are returned by the query based on certain criteria. It takes a query object as its value, which can contain one or more key-value pairs. The key represents the name of the field you want to query, and the value represents the condition that the field must meet for the document to be returned by the query. Let's say we want to find documents where we have a release date of the book present so our query will be something like this:
Sexists is a keyword. It is used to check if the key exists in the document or not.
-
Projection: The projection parameter allows you to specify which fields should be included or excluded from the returned documents. It takes an object as its value, where the keys represent the names of the fields you want to include or exclude, and the values are either 1 (to include the field) or 0 (to exclude the field). To find all documents in the BookList collection where the author_name field is "Agatha Christie", and include only the book name field, we can use the following query:
-
Options: The options parameter allows you to modify the behavior of the query in various ways. Here are some commonly used options:
-
sort: The sort() method in MongoDB can be used to sort the result set of a query. To use sort(), we first need to select the collection you want to query using the db.collection notation. You can then call find() on the selected collection and pass a query object to retrieve the documents you want to sort. Finally, you can call sort() on the result set and pass a sort object to specify the sorting order. We use sort functionality as defined by the syntax: db.collection.find().sort({ field: 1 }). 1 stands for ascending order and -1 stands for descending order. We can also sort by multiple fields at once. For our collection, let's sort by the book name alphabetically.
db.BookList.find().sort({'book_name':1})
-
limit: Used to limit the number of returned documents. Suppose we need only the top two results so we use a method limit(value) along with the find() method to limit our number of matched results to value.
We use a command like: db.BookList.find().limit(2).
By doing this, we get the result:
-
skip: Used to skip a specified number of documents from the beginning of the result set. Suppose we want to skip() the first document so we can use a command like this:
db.BookList.find().skip(1)
If there are no matching documents, MongoDB find() does not return anything on the command prompt.
We do not have any book name like 'David Copperfield', so when we query for a book name with it using the find() method using the command :
we get a response as given below.
Return Values
So, as we have seen from the above examples, MongoDB Find() returns a cursor to the documents that meet the search criteria. Even though the method says it "returns documents," it returns a cursor to the documents.
Examples
We can also use a toArray() function with MongoDB Find(). To convert the results returned by the find() method to an array, you can use the toArray() method. The toArray() method returns an array that contains all the documents returned by the find() method.
Syntax: db.collectionName.find().toArray()
In addition to these, MongoDB also provides several other related methods, such as findOne(), and findAndModify(). These methods can be used to perform more complex queries and operations on the result set.
-
findOne(): The findOne() method in MongoDB is similar to the find() method, but it only returns the first document that matches the specified query criteria. This can be useful when you only need to retrieve a single document, rather than a set of documents. The syntax remains the same as the find() method: db.collectionName.findOne({'field':'value'})
Suppose, in our collection, we have two books whose author is Agatha Christie however if we query as:
db.BookList.findOne({'author_name':'Agatha Christie'})
We see we get the first matched document. You can also use various options with findOne(), such as the sort() and projection options.
-
findAndModify(): The findAndModify() method in MongoDB allows you to atomically modify a document and return the modified document in a single operation.
To use findAndModify(), you first need to select the collection you want to modify using the db.collection notation. You can then call findAndModify() on the selected collection and pass a query object to specify which document to modify:
This will modify the document where the specified field has the specified value and set field2 to value2. The new option is set to true, which means that the modified document will be returned in the result set.
Let's say we want to update one of the book names of Agatha Christie:
Perform Complex Queries Using MongoDB Find()
There are several complex queries that we can create using find. You can also use the $gt, $lt, $gte, and $lte operators to perform range queries and the $in operator to match any value in a specified array.
Suppose, we need the entries of all books where the author name is not equal to ‘Agatha Christie’, we use the ne function for this.
So we can use a query like: db.BookList.find({author_name:{$ne:'Agatha Christie'}})
Another great example is, Suppose we want a list of booknames, so we use the in function. Remember we use the '$' operator for specific commands like 'gte','ne','eq' etc. Let’s say our query is to find a list of book names where the name is either Atomic Habits or The Psychology of Money. So we use a query like:
db.BookList.find({book_name:{$in:["Atomic Habits","The Psychology of Money"]}})
FAQs
Q: What is the find() method in MongoDB?
A: The find() method is used to retrieve documents from a collection in MongoDB. It returns a cursor object that points to the documents that match the specified query criteria.
Q: How do I specify query criteria in the find() method?
A: To specify query criteria in the find() method, you can pass a document that contains the query criteria as an argument. For example, to find all documents in a collection where the book_name field is equal to Atomic Habits, you can use the following code:
db.collectionName.find({book_name: "Atomic Habits"})
Q: Can I use regular expressions in the query criteria?
A: Yes, you can use regular expressions in the query criteria. For example, to find all documents in a collection where the name field starts with the letter "S", you can use the following code:
db.collectionName.find({name: /^S/})
Q: How do I limit the number of documents returned by the find() method?
A: To limit the number of documents returned by the find() method, you can use the limit() method. For example, to find the first 10 documents in a collection, you can use the following code:
db.collectionName.find().limit(10)
Conclusion
- The MongoDB Find() method is a powerful tool for retrieving data from collections in the database.
- It provides a flexible way to retrieve only the documents that match specific criteria and to include or exclude specific fields from the result set.
- We can sort, limit, and skip results and use them with other functions to build complex queries to find our target goals. Understanding how to use the find() method effectively is crucial for working with MongoDB databases.