0
0
MongoDBquery~5 mins

Query filter syntax in MongoDB

Choose your learning style9 modes available
Introduction
Query filters help you find only the data you want from a big collection. They act like a search tool to pick matching items.
When you want to find all users older than 25 in a user list.
When you need to get all orders with status 'shipped'.
When you want to find products priced below $50.
When you want to search for documents containing a specific word.
When you want to filter records by date or category.
Syntax
MongoDB
{ field: value }
The filter is a JSON object where keys are field names and values are what you want to match.
You can use operators like $gt (greater than), $lt (less than), $eq (equals) inside the filter.
Examples
Find documents where the age field is exactly 30.
MongoDB
{ age: 30 }
Find documents where the price is less than 50.
MongoDB
{ price: { $lt: 50 } }
Find documents where status is either 'shipped' or 'delivered'.
MongoDB
{ status: { $in: ["shipped", "delivered"] } }
Find documents where the name starts with the letter 'A'.
MongoDB
{ name: { $regex: "^A" } }
Sample Program
This query finds all orders where the status field is exactly 'shipped'.
MongoDB
db.orders.find({ status: "shipped" })
OutputSuccess
Important Notes
Filters are case-sensitive by default.
You can combine multiple conditions using $and, $or operators.
If you want to match a field that does not exist, use $exists operator.
Summary
Query filters let you pick only the data you want by specifying conditions.
Filters use JSON objects with field names and values or operators.
You can use many operators to create flexible and powerful searches.