Introduction
Learn how to use query operators in MongoDB to filter and retrieve documents based on specific criteria using the mongosh
shell interface.
Connecting to MongoDB
Before querying documents, ensure you are connected to your MongoDB server:
Example: Connecting to MongoDB
mongosh
This command starts the mongosh
shell and connects to the default MongoDB server running locally.
Switching to a Database
Switch to the database where your collection resides using the use
command:
Example: Switching to a Database
use mydatabase
This command switches to the “mydatabase” database. Replace mydatabase
with your database name.
Query Operators
Comparison Operators
Comparison operators allow you to compare values in MongoDB queries:
Example: Comparison Operators
db.mycollection.find({ age: { $gt: 25 } })
This command finds documents in the mycollection
collection where the age
field is greater than 25.
Logical Operators
Logical operators perform logical operations on expressions and return true or false:
Example: Logical Operators
db.mycollection.find({ $and: [{ status: "active" }, { age: { $gte: 18 } }] })
This command finds documents where the status
is “active” and age
is greater than or equal to 18.
Element Operators
Element operators allow you to query documents based on the existence of fields:
Example: Element Operators
db.mycollection.find({ email: { $exists: true } })
This command finds documents in the mycollection
collection where the email
field exists.
Array Operators
Array operators allow you to query documents that match conditions on array fields:
Example: Array Operators
db.mycollection.find({ tags: { $all: ["mongodb", "database"] } })
This command finds documents where the tags
array contains both “mongodb” and “database”.
Evaluation Operators
Evaluation operators allow you to perform expression evaluations within MongoDB queries:
Example: Evaluation Operators
db.mycollection.find({ $expr: { $gt: ["$qty", "$rate"] } })
This command finds documents where the value of the qty
field is greater than the value of the rate
field.
Regular Expression Operators
Regular expression operators allow you to perform queries using regular expressions:
Example: Regular Expression Operators
db.mycollection.find({ name: { $regex: "^J" } })
This command finds documents where the name
field starts with the letter “J”.
Conclusion
Query operators in MongoDB provide powerful tools for filtering and retrieving documents based on specific criteria. Experiment with different operators and combinations to meet your application’s needs.