Show List
Querying data with MongoDB
In MongoDB, you can query data using the db.collection.find()
method. This method takes a query object as an argument and returns a cursor to the documents that match the query. Here are some examples of how to query data with MongoDB:
- Querying for all documents in a collection:
To retrieve all documents in a collection, you can simply call the
find()
method without any arguments. For example, to retrieve all documents in the "customers" collection, you can use the following command:
luaCopy code
db.customers.find()
- Querying for documents that match a specific field:
To retrieve documents that match a specific field, you can pass a query object to the
find()
method. For example, to retrieve all documents in the "customers" collection where the name field is "John Doe", you can use the following command:
cssCopy code
db.customers.find({ name: "John Doe" })
- Querying for documents that match multiple fields:
To retrieve documents that match multiple fields, you can pass a query object with multiple key-value pairs to the
find()
method. For example, to retrieve all documents in the "customers" collection where the name is "John Doe" and the age is 30, you can use the following command:
phpCopy code
db.customers.find({ name: "John Doe", age: 30 })
- Querying for documents that match a range of values: To retrieve documents that match a range of values, you can use MongoDB's query operators. For example, to retrieve all documents in the "customers" collection where the age is greater than or equal to 30, you can use the following command:
cssCopy code
db.customers.find({ age: { $gte: 30 } })
- Querying for documents that match a pattern: To retrieve documents that match a pattern, you can use MongoDB's regular expression (regex) syntax. For example, to retrieve all documents in the "customers" collection where the name starts with "J", you can use the following command:
javascriptCopy code
db.customers.find({ name: /^J/ })
These are some examples of how to query data with MongoDB. MongoDB also provides a rich set of query operators and aggregation framework for more complex queries.
Leave a Comment