๐ 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
- JavaScript
- mongosh
- C#
const cursor = await books.find({ totalInventory: 5 });
await cursor.forEach((b) => {
console.log(b);
});
db.books.find({ totalInventory: 5 });
var booksWithTotalInventoryOf5 = Builders<Book>.Filter.Eq(b => b.TotalInventory, 5);
List<Book> filteredBooks = booksCollection.Find(booksWithTotalInventoryOf5).ToList<Book>();
if(filteredBooks != null)
{
foreach(var book in filteredBooks)
{
Console.WriteLine($"Book Title: {book.Title} - Total Inventory: {book.TotalInventory}");
}
}
2. Find all books with more than 300 pages.โ
Answer
- JavaScript
- mongosh
- C#
const cursor = await books.find({ pages: {$gt: 300} });
await cursor.forEach((b) => {
console.log(b);
});
db.books.find({ pages: {$gt: 300} });
var booksWithMoreThan300Pages = Builders<Book>.Filter.Gt(b => b.Pages, 300);
List<Book> filteredBooks = booksCollection.Find(booksWithMoreThan300Pages).ToList<Book>();
if(filteredBooks != null)
{
foreach(var book in filteredBooks)
{
Console.WriteLine($"Book Title: {book.Title} - Pages: {book.Pages}");
}
}
3. Find books in the Science genre that are more than 300 pages long.โ
Answer
- JavaScript
- mongosh
- C#
const cursor = await books.find( { "genres": "Science", pages: {$gt: 300} } );
await cursor.forEach((b) => {
console.log(b);
});
db.books.find({ "genres": "Science", pages: {$gt: 300} });
var booksWithGenreScienceAndMoreThan300Pages = Builders<Book>.Filter.And(Builders<Book>.Filter.AnyEq(b => b.Genres, "Science"), Builders<Book>.Filter.Gt(b => b.Pages, 300));
var filteredBooks = booksCollection
.Find(booksWithGenreScienceAndMoreThan300Pages)
.ToList();
foreach (var book in filteredBooks)
{
Console.WriteLine($"{book.Title} - Pages: {book.Pages}");
}