MongoDB – Query Document
After creating the collections and inserting documents, you can query the database to retrieve information. For example:
- Find all customers:
db.customers.find()
- Find a specific policy:
db.policies.find({ policyNumber: "INS-2023-001" })
- Find claims for a particular policy:
db.claims.find({ policyNumber: "INS-2023-001" })
- Find payments for a specific customer:
db.payments.find({ customerId: 1 })
In MongoDB, querying documents is done using the find() method. This method allows you to search for documents in a collection based on specific criteria.
1. Basic Query
A basic query in MongoDB is performed using db.collection.find() to retrieve all documents from a collection.
Example: Query all documents in a collection:
db.customers.find()
This query retrieves all documents from the customers collection.
2. Query with Condition (Filtering Documents)
You can filter the documents based on specific conditions. MongoDB uses JSON-like query syntax for this.
Example: Query with condition ( _id equals 1):
db.customers.find({ _id: 1 })
This query retrieves the document where the _id is 1.
Example: Query with multiple conditions (find customers with first name “John” and last name “Doe”):
db.customers.find({ firstName: "John", lastName: "Doe" })
This query retrieves documents that match both conditions.
Example: Query with comparison operators:
db.customers.find({ age: { $gt: 30 } }) // Greater than 30
This retrieves customers who are older than 30. MongoDB supports various comparison operators, such as:
- $gt : Greater than
- $lt : Less than
- $gte : Greater than or equal to
- $lte : Less than or equal to
- $eq : Equal to
- $ne : Not equal to
3. Logical Operators
MongoDB allows you to use logical operators to combine multiple conditions.
Example: Use $and to combine conditions:
db.customers.find({
$and: [
{ firstName: "John" },
{ lastName: "Doe" }
]
})
This retrieves customers where both conditions are true.
Example: Use $or to retrieve customers with either “John” or “Jane”:
db.customers.find({
$or: [
{ firstName: "John" },
{ firstName: "Jane" }
]
})
This retrieves customers where either condition is true.
Example: Use $not to find customers where age is not 30:
db.customers.find({ age: { $not: { $eq: 30 } } })
This will return all customers whose age is not equal to 30.
4. Query with Projection (Selecting Specific Fields)
You can also specify which fields to return in your query results using projection. By default, MongoDB returns all fields of the document. To limit or include specific fields, use projection.
Example: Query to return only specific fields (firstName and lastName):
db.customers.find({}, { firstName: 1, lastName: 1 })
In this query, {} is the condition (all documents), and { firstName: 1, lastName: 1 } is the projection, which means only the firstName and lastName fields will be returned. The value 1 indicates the field should be included.
Example: Query to exclude specific fields (excluding contactInfo):
db.customers.find({}, { contactInfo: 0 })
This will return all fields except the contactInfo field.
5. Query with Sorting
MongoDB supports sorting of the results. The sort() method allows you to order documents based on one or more fields.
Example: Query and sort by lastName in ascending order:
db.customers.find().sort({ lastName: 1 })
The value 1 indicates ascending order.
Example: Query and sort by age in descending order:
db.customers.find().sort({ age: -1 })
The value -1 indicates descending order.
6. Query with Limit and Skip
MongoDB provides limit() and skip() methods to limit the number of documents returned and skip a number of documents, respectively.
Example: Limit the number of documents returned to 2:
db.customers.find().limit(2)
This will return only the first 2 documents from the collection.
Example: Skip the first 2 documents and return the next 2:
db.customers.find().skip(2).limit(2)
This will skip the first 2 documents and return the next 2.
7. Query with Regular Expressions
You can use regular expressions to search for patterns in strings.
Example: Query customers with a first name starting with “J”:
db.customers.find({ firstName: /^J/ })
This uses a regular expression to match any customer whose first name starts with “J”.
Example: Case-insensitive search for last name “doe”:
db.customers.find({ lastName: /doe/i })
The i flag makes the search case-insensitive.
8. Query for Nested Fields
If documents have nested fields, you can query those as well.
Example: Query customers who live in Springfield (nested field contactInfo.address):
db.customers.find({ "contactInfo.address": "Springfield" })
This query retrieves customers whose address is “Springfield”.
Example: Query customers with phone numbers starting with “123” (nested field contactInfo.phone):
db.customers.find({ "contactInfo.phone": /^123/ })
9. Query with Array Operators
MongoDB supports querying arrays within documents using operators like $all, $size, $elemMatch, etc.
Example: Query customers who have more than 1 policy:
db.customers.find({ "policies.1": { $exists: true } })
This checks if the second element in the policies array exists, which means the customer has more than one policy.
Example: Query customers whose policies array contains a specific policy number:
db.customers.find({ "policies.policyNumber": "INS-2023-001" })
10. Aggregation Queries (Advanced)
MongoDB also provides the aggregation framework for more complex queries, such as grouping, sorting, or performing calculations across documents. This is often used for reporting and data analysis.
Example: Aggregate customers by city:
db.customers.aggregate([
{ $group: { _id: "$contactInfo.city", count: { $sum: 1 } } }
])
This groups customers by city and counts the number of customers in each city.
Summary of Common Query Operations
Operation | Query Syntax Example |
---|---|
Find all documents | db.customers.find() |
Find by condition | db.customers.find({ firstName: “John” }) |
Find with projection | db.customers.find({}, { firstName: 1, lastName: 1 }) |
Sort results | db.customers.find().sort({ age: -1 }) |
Limit results | db.customers.find().limit(3) |
Skip results | db.customers.find().skip(3) |
Regex search | db.customers.find({ firstName: /^J/ }) |
Nested field query | db.customers.find({ “contactInfo.address”: “Springfield” }) |
Array query | db.customers.find({ “policies.policyNumber”: “INS-2023-001” }) |
Conclusion
MongoDB provides a powerful and flexible query language to search and retrieve documents. You can perform simple queries, use conditions, sort and limit results, and even work with nested fields and arrays. The MongoDB query language is highly flexible, making it easy to retrieve and manage data based on various conditions and requirements.
Recent Comments