codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

12 / 65 topics
12Querying Basics13Find Queries14Projection15Sorting and Limiting16Aggregation Framework17Operators in MongoDB18Text Search
Tutorials/MongoDB/Querying Basics
🍃MongoDB

Querying Basics

Updated 2026-04-20
3 min read

Introduction

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. One of its core features is the ability to perform complex queries on these documents. This tutorial will cover the basics of querying in MongoDB, including how to construct queries, use query operators, and understand the concept of projection.

Understanding Documents

Before diving into querying, it's important to understand what a document looks like in MongoDB. A document is a JSON-like data structure that can contain nested arrays and objects. Here’s an example:

{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  },
  "hobbies": ["reading", "traveling"]
}

Basic Queries

Finding Documents

To find documents in a collection, you use the find() method. The simplest query retrieves all documents from a collection:

db.collection.find()

This will return all documents in the specified collection.

Querying with Conditions

You can specify conditions to filter documents using key-value pairs. For example, to find all users named "John Doe":

db.collection.find({ name: "John Doe" })

Using Comparison Operators

MongoDB supports a variety of comparison operators:

  • $eq: Equal to
  • $ne: Not equal to
  • $gt: Greater than
  • $gte: Greater than or equal to
  • $lt: Less than
  • $lte: Less than or equal to

Example: Find users older than 25:

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

Logical Operators

Logical operators allow you to combine multiple conditions:

  • $and: All conditions must be true.
  • $or: At least one condition must be true.
  • $not: Inverts the condition.

Example: Find users who are either older than 30 or named "John Doe":

db.collection.find({
  $or: [
    { age: { $gt: 30 } },
    { name: "John Doe" }
  ]
})

Projection

Projection allows you to specify which fields to include or exclude in the returned documents. This can improve performance by reducing the amount of data transferred.

Including Fields

To include specific fields, set their values to 1:

db.collection.find({}, { name: 1, age: 1 })

This will return only the name and age fields for each document.

Excluding Fields

To exclude specific fields, set their values to 0:

db.collection.find({}, { address: 0, hobbies: 0 })

This will return all fields except address and hobbies.

Special Projections

  • _id: By default, _id is included. To exclude it, set it to 0.
  • $slice: Use this operator to limit the number of elements in an array.

Example: Return only the first two hobbies:

db.collection.find({}, { hobbies: { $slice: 2 } })

Sorting and Limiting Results

Sorting

To sort results, use the sort() method. The argument is a document where field names are keys and values specify the sort order (1 for ascending, -1 for descending).

Example: Sort users by age in descending order:

db.collection.find().sort({ age: -1 })

Limiting Results

To limit the number of documents returned, use the limit() method.

Example: Return only the first 5 documents:

db.collection.find().limit(5)

Best Practices

  • Indexing: Use indexes to improve query performance. Create indexes on fields that are frequently used in queries.

  • Efficient Queries: Avoid using $where clauses and try to use indexed fields for filtering.

  • Projection: Always use projection to limit the amount of data returned, especially when dealing with large collections.

  • Pagination: Use skip() and limit() together for pagination. However, be cautious as skip() can become slow with large offsets.

Conclusion

This tutorial covered the basics of querying in MongoDB, including how to construct queries, use query operators, and understand projection. By mastering these fundamentals, you'll be able to efficiently retrieve and manipulate data stored in MongoDB collections.


PreviousSchema Design PrinciplesNext Find Queries

Recommended Gear

Schema Design PrinciplesFind Queries