Finding Documents

Lesson 6
Author : Afrixi
Last Updated : February, 2023
MongoDB - noSQL Database
This course covers the basics of working with MongoDB.

In MongoDB, you can search for documents in a collection using the find() method. The find() method returns a cursor object that points to the matching documents.

Here is an example of using the find() method to find all documents in a collection:

db.collectionName.find()

To find a document with a specific value in a field, you can pass a query object to the find() method. For example, to find all documents where the name field equals “John”, you can use the following command:

db.collectionName.find({ name: "John" })

You can also use comparison operators to search for documents with values greater than or less than a certain value. For example, to find all documents where the age field is greater than 25, you can use the following command:

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

The $gt operator stands for “greater than”.

You can also chain multiple conditions together using the $and and $or operators. For example, to find all documents where the name field is “John” and the age field is greater than 25, or where the name field is “Jane” and the age field is less than 30, you can use the following command:

db.collectionName.find({
  $or: [
    { name: "John", age: { $gt: 25 } },
    { name: "Jane", age: { $lt: 30 } }
  ]
})

This command uses the $or operator to specify two conditions. The first condition uses the $and operator to specify that the name field must be “John” and the age field must be greater than 25. The second condition specifies that the name field must be “Jane” and the age field must be less than 30.

You can also use other operators, such as $in, $nin, and $regex, to search for documents based on specific criteria. For more information on querying documents in MongoDB, see the official documentation.