Introduction
The MongoDB Query API allows you to retrieve and manipulate data from MongoDB databases using various query operators and methods.
Basic Queries
Perform basic queries to retrieve documents from a collection:
Example: Basic Query
db.collection.find({ "field": value })
Replace collection
with your collection name, field
with the document field to query, and value
with the value to match.
Query Operators
Use query operators to specify conditions in MongoDB queries:
Example: Query with Operator
db.collection.find({ "age": { $gt: 30 } })
This query finds documents where the “age” field is greater than 30.
Projection
Limit fields returned in query results using projection:
Example: Projection
db.collection.find({}, { "name": 1, "age": 1 })
This query returns only the “name” and “age” fields from documents in the collection.
Sorting
Sort query results based on one or more fields:
Example: Sorting
db.collection.find().sort({ "age": 1 })
This query sorts documents in ascending order based on the “age” field.
Limit and Skip
Limit and skip results in MongoDB queries:
Example: Limit and Skip
db.collection.find().limit(5).skip(10)
This query limits results to 5 documents, skipping the first 10 documents in the collection.
Conclusion
Understanding the MongoDB Query API is essential for efficiently querying data from MongoDB databases. With basic and advanced query operations, you can retrieve, manipulate, and analyze data as per your application’s requirements.