MongoDB Query Operators 🎯

beginner
7 min

MongoDB Query Operators 🎯

Welcome to our tutorial on MongoDB Query Operators! In this lesson, we'll explore various operators that will help you manipulate and filter your data effectively. Let's dive right in!

Introduction 📝

MongoDB, a popular NoSQL database, uses a flexible data model and powerful query language to store and manage data. In this lesson, we'll focus on understanding different query operators that will help you filter and manipulate your data in MongoDB.

Basic Query Operators 💡

$eq 💡

The $eq operator is used to filter documents where the specified field is equal to a given value.

javascript
db.collection.find({ field: value })

📝 Note: Replace collection with the name of your collection, field with the field you want to filter, and value with the desired value.

Example:

javascript
// Suppose we have a collection named 'users' db.users.find({ age: 25 })

$gt 💡

The $gt operator is used to filter documents where the specified field is greater than a given value.

javascript
db.collection.find({ field: { $gt: value } })

Example:

javascript
db.users.find({ age: { $gt: 25 } })

$lt 💡

The $lt operator is used to filter documents where the specified field is less than a given value.

javascript
db.collection.find({ field: { $lt: value } })

Example:

javascript
db.users.find({ age: { $lt: 20 } })

$gte 💡

The $gte operator is used to filter documents where the specified field is greater than or equal to a given value.

javascript
db.collection.find({ field: { $gte: value } })

Example:

javascript
db.users.find({ age: { $gte: 25 } })

$lte 💡

The $lte operator is used to filter documents where the specified field is less than or equal to a given value.

javascript
db.collection.find({ field: { $lte: value } })

Example:

javascript
db.users.find({ age: { $lte: 30 } })

Advanced Query Operators 💡

$in 💡

The $in operator is used to filter documents where the specified field is present in an array of allowed values.

javascript
db.collection.find({ field: { $in: [value1, value2, ...] } })

Example:

javascript
db.users.find({ age: { $in: [25, 30, 35] } })

$nin 💡

The $nin operator is used to filter documents where the specified field is not present in an array of allowed values.

javascript
db.collection.find({ field: { $nin: [value1, value2, ...] } })

Example:

javascript
db.users.find({ age: { $nin: [18, 20, 21] } })

Quiz 📝

Quick Quiz
Question 1 of 1

Which operator is used to filter documents where the specified field is equal to a given value?

Conclusion 💡

Mastering MongoDB query operators will empower you to effectively manage and manipulate your data. By understanding the basic and advanced operators, you'll be well on your way to becoming a MongoDB pro!

Stay tuned for our next lesson, where we'll dive deeper into MongoDB querying and aggregation. Happy coding! 🎉