๐ WHERE โ .find()
Similar to SQL's WHERE
clause, the .find()
method in MongoDB retrieves documents from a collection that matches a specified query.
Syntaxโ
db.collection.find({ <query> })
<query>
: Specifies conditions to filter documents
Example: Find all books from 2020โ
db.books.find({ year: 2020 });
Equivalent SQL queryโ
SELECT * FROM books WHERE year = 2020;
Filtering with find()
โ
The find()
method takes a document as its first argument. This document specifies the filter criteria. You can use a variety of expressions within the filter document:
- Comparison operators:
$eq
(equals),$ne
(not equals),$gt
(greater than),$lt
(less than),$gte
(greater than or equals),$lte
(less than or equals),$in
(in an array),$nin
(not in an array) - Logical operators:
$and
,$or
,$not
- Element operators:
$exists
(check for field existence),$type
(check data type) - Evaluation operators:
$regex
(regular expression matching),$where
(JavaScript code execution) - Geo-spatial operators: For location-based queries
- Array operators: For querying arrays
Now, let's utilize a few MongoDB operators and create more sophisticated queries:
$or and $gt operatorsโ
Suppose we want to get all of the books that were written in 2010 or that have more than 200 pages.
SELECT * FROM books WHERE year = 2010 OR pages > 200;
Equivalent MongoDB query:
db.books.find({
$or: [
{ year: 2010 }, // <--- 1st condition
{ pages: { $gt: 200 } }, // <--- 2nd condition
],
});
$and operatorโ
This time, instead of OR, let's query using AND:
SELECT * FROM books WHERE year = 2010 AND pages > 200;
Equivalent MongoDB query:
db.books.find({
$and: [
{ year: 2010 }, // <--- 1st condition
{ pages: { $gt: 200 } }, // <--- 2nd condition
],
});
Shorthand $andโ
When we are querying on two different fields and want to utilize $and, we can do so by passing a document with all the conditions, like this:
db.books.find({ year: 2010, pages: { $gt: 200 } });
As you can see, we don't have to pass an array of conditions. MongoDB implicitly considers this as $and.
๐ Challengeโ
Now, translate the following into a MongoDB query.
1. Find all books where totalInventory
is exactly 5.โ
Answer
db.books.find({ totalInventory: 5 });
2. Find all books with more than 300 pages.โ
Answer
db.books.find({ pages: {$gt: 300} });
3. Find books in the Science
genre that are more than 300 pages long.โ
Answer
db.books.find({ genres: "Science", pages: {$gt: 300} });