Create New Post

MongoDB - Find

In MongoDB, the find method is used to query documents in a collection. It returns a cursor to the documents that match the specified criteria. Here's how you can use the find method:

Basic find Syntax:

db.collection_name.find({ criteria });

  • collection_name: The name of the collection you want to query.
  • criteria: The criteria or conditions to filter the documents.

Example:

Let's say you have a collection named users, and you want to find all documents where the age is greater than 25:

db.users.find({ age: { $gt: 25 } });

This query will return a cursor to all documents in the users collection where the age field is greater than 25.

Projection:

You can also specify which fields to include or exclude in the result using projection. For example, if you only want to retrieve the name and email fields:

db.users.find({ age: { $gt: 25 } }, { name: 1, email: 1, _id: 0 });

In this example, 1 indicates that the field should be included, and _id: 0 indicates that the _id field should be excluded.

Sorting:

You can sort the results based on a field. For example, to sort by the name field in ascending order:

db.users.find({ age: { $gt: 25 } }).sort({ name: 1 });

Here, 1 indicates ascending order, and -1 would indicate descending order.

Limiting:

You can limit the number of documents returned using the limit method. For example, to limit the result to 10 documents:

db.users.find({ age: { $gt: 25 } }).limit(10);

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

85203