A Complete Guide to MongoDB Queries with Examples
Tags: beginners, programming, mongodb, node
Published: 2023-07-11 15:02:27



MongoDB is a popular NoSQL database that stores data in JSON-like documents. MongoDB provides a powerful and flexible query language that allows you to perform various operations on your data. In this blog post, we will look at some common MongoDB queries examples with answers for dev platform.

## Query 1: Find all documents in a collection

To find all documents in a collection, you can use the `find()` method without any arguments. For example, to find all documents in the `users` collection, you can use:

```javascript
db.users.find()
```

This will return a cursor that you can iterate over to access the documents. You can also use the `pretty()` method to format the output:

```javascript
db.users.find().pretty()
```

## Query 2: Find documents that match a condition

To find documents that match a condition, you can use the `find()` method with a query filter document as an argument. The query filter document specifies the criteria for selecting the documents. For example, to find all users who have the role of "admin", you can use:

```javascript
db.users.find({role: "admin"})
```

You can also use comparison operators, logical operators, and other operators to specify more complex conditions. For example, to find all users who have the role of "admin" or "moderator", and who have more than 100 posts, you can use:

```javascript
db.users.find({$or: [{role: "admin"}, {role: "moderator"}], posts: {$gt: 100}})
```

## Query 3: Find documents and project only specific fields

To find documents and project only specific fields, you can use the `find()` method with a projection document as a second argument. The projection document specifies which fields to include or exclude in the result. For example, to find all users and project only their name and email fields, you can use:

```javascript
db.users.find({}, {name: 1, email: 1})
```

By default, the `_id` field is always included in the result, unless you explicitly exclude it. For example, to find all users and project only their name and email fields, and exclude the `_id` field, you can use:

```javascript
db.users.find({}, {name: 1, email: 1, _id: 0})
```

## Query 4: Find documents and sort them by a field

To find documents and sort them by a field, you can use the `sort()` method on the cursor returned by the `find()` method. The `sort()` method takes a sort document as an argument, which specifies the field(s) to sort by and the order (ascending or descending). For example, to find all users and sort them by their name in ascending order, you can use:

```javascript
db.users.find().sort({name: 1})
```

To sort by multiple fields, you can specify them in the sort document in the order of priority. For example, to find all users and sort them by their role in ascending order, and then by their name in descending order, you can use:

```javascript
db.users.find().sort({role: 1, name: -1})
```

## Query 5: Find documents and limit the number of results

To find documents and limit the number of results, you can use the `limit()` method on the cursor returned by the `find()` method. The `limit()` method takes a positive integer as an argument, which specifies the maximum number of documents to return. For example, to find all users and limit the result to 10 documents, you can use:

```javascript
db.users.find().limit(10)
```

You can also combine the `limit()` method with the `sort()` method to find documents and limit them after sorting. For example, to find all users, sort them by their name in ascending order, and limit the result to 10 documents, you can use:

```javascript
db.users.find().sort({name: 1}).limit(10)
```

## Query 6: Find documents and skip some results

To find documents and skip some results, you can use the `skip()` method on the cursor returned by the `find()` method. The `skip()` method takes a positive integer as an argument, which specifies the number of documents to skip before returning the result. For example, to find all users and skip the first 10 documents, you can use:

```javascript
db.users.find().skip(10)
```

You can also combine the `skip()` method with the `limit()` method to find documents and skip some results before limiting them. For example, to find all users, skip the first 10 documents, and limit the result to 10 documents, you can use:

```javascript
db.users.find().skip(10).limit(10)
```

## Query 7: Find documents that match a regular expression

To find documents that match a regular expression, you can use the `$regex` operator in the query filter document. The `$regex` operator takes a regular expression as a value, which specifies the pattern to match. For example, to find all users whose name starts with "A", you can use:

```javascript
db.users.find({name: {$regex: /^A/}})
```

You can also use the `$options` operator to specify additional options for the regular expression, such as case-insensitivity or multiline matching. For example, to find all users whose name contains "a" or "A", you can use:

```javascript
db.users.find({name: {$regex: /a/, $options: "i"}})
```

## Query 8: Find documents that match an array value

To find documents that match an array value, you can use the `$in` operator in the query filter document. The `$in` operator takes an array as a value, which specifies the values to match. For example, to find all users who have either "admin" or "moderator" as their role, you can use:

```javascript
db.users.find({role: {$in: ["admin", "moderator"]}})
```

You can also use the `$nin` operator to find documents that do not match any of the values in the array. For example, to find all users who do not have either "admin" or "moderator" as their role, you can use:

```javascript
db.users.find({role: {$nin: ["admin", "moderator"]}})
```

## Query 9: Find documents that match an array element

To find documents that match an array element, you can use the dot notation in the query filter document. The dot notation allows you to access the elements of an array by their index. For example, to find all users who have "java" as their first skill in the skills array, you can use:

```javascript
db.users.find({"skills.0": "java"})
```

You can also use comparison operators and other operators to specify more complex conditions on the array elements. For example, to find all users who have more than 3 skills in the skills array, you can use:

```javascript
db.users.find({skills: {$size: {$gt: 3}}})
```

## Query 10: Find documents that match a subdocument

To find documents that match a subdocument, you can use the dot notation in the query filter document. The dot notation allows you to access the fields of a subdocument by their name. For example, to find all users who have a profile subdocument with a bio field containing "developer", you can use:

```javascript
db.users.find({"profile.bio": {$regex: /developer/}})
```

You can also use comparison operators and other operators to specify more complex conditions on the subdocument fields. For example, to find all users who have a profile subdocument with an age field between 20 and 30, you can use:

```javascript
db.users.find({"profile.age": {$gte: 20, $lte: 30}})
```


## Conclusion

In this blog post, we have seen some common MongoDB queries examples with answers for dev platform. MongoDB offers a rich and expressive query language that allows you to manipulate your data in various ways. You can learn more about MongoDB queries from the official documentation here: https://docs.mongodb.com/manual/crud/

---
🌟 **Thank You for Joining the Journey!** 🌟

>I hope you found this blog post informative and engaging. Your support means the world to me, and I'm thrilled to have you as part of my community. To stay updated on my latest content.


📌 **Follow me on Social Media!** 📌


🌐 [Visit my Website](https://raj-rathod.github.io/rajesh-rathore/)
📢 [Connect with me on Twitter](https://twitter.com/Rajesh946055)
📷 [Follow me on Instagram](https://www.instagram.com/raj_rathod1313/?hl=en)
📚 [Connect on LinkedIn](https://www.linkedin.com/in/rajesh-rathore-0501/)
📌 [Check out my GitHub](https://github.com/raj-rathod)

💌 **A Special Message to You!** 💌

To all my dedicated readers and fellow tech enthusiasts, I want to express my gratitude for your continuous support. Your engagement, comments, and feedback mean the world to me. Let's keep learning, growing, and sharing our passion for development!

👥 Let's Stay Connected! 👥
If you enjoy my content and want to stay in the loop with my latest posts, please consider following me on my social media platforms. Your support is invaluable.

Thank you for being a part of this amazing journey! 🚀

---