- Constructing Queries on Databases, Collections, ...
- Constructing Queries on Databases, Collections, ...
MongoDB's query language, based on the JSON format, provides a powerful and flexible way to
interact with your data. Let's explore some fundamental query operations:
Basic Queries
● Finding All Documents:
db.collectionName.find()
● Projection:
db.collectionName.find({}, { field1: 1, field2: 1 }) // Project
only field1 and field2
Query Operators
● Comparison Operators:
db.collectionName.find({ age: { $gt: 18, $lt: 30 } }) // Age
between 18 and 30
● Logical Operators:
db.collectionName.find({ $or: [{ age: { $gt: 30 } }, { city: "New
York" }] }) // Age greater than 30 OR city is New York
● Regular Expressions:
db.collectionName.find({ name: /John/i }) // Case-insensitive
search for "John"
● Array Operators:
db.collectionName.find({ hobbies: "coding" }) // Find documents
with "coding" in the hobbies array
Aggregation Pipeline
The aggregation pipeline allows you to group, transform, and summarize data.
db.collectionName.aggregate([
{ $group: { _id: "$country", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
])
This pipeline groups documents by country, counts the number of documents in each group,
and sorts the results by total count in descending order.
Example: Finding Users Older Than 30
db.users.find({ age: { $gt: 30 } })