0% found this document useful (0 votes)
2 views2 pages

- Constructing Queries on Databases, Collections, ...

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views2 pages

- Constructing Queries on Databases, Collections, ...

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 2

Constructing Queries on Databases, Collections, and Documents

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()

● Finding Documents by Specific Field:


db.collectionName.find({ field: "value" })

● 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 } })

Example: Finding Products Priced Between $10 and $20


db.products.find({ price: { $gt: 10, $lt: 20 } })

Example: Finding Documents with a Specific Tag


db.posts.find({ tags: "mongodb" })
Remember to practice and experiment with different query combinations to fully leverage
MongoDB's querying capabilities. By understanding the core concepts and operators, you can
efficiently retrieve and analyze your data.
Would you like to delve deeper into a specific query operation or explore a more complex
example?

You might also like