Skip to content

MongoDB Query Document

MongoDB provides powerful querying capabilities to precisely find, filter, and retrieve documents.

Basic Queries

find() Method

javascript
db.collection.find(query, projection)

Query All Documents

javascript
// Query all documents
db.users.find()

// Pretty print output
db.users.find().pretty()

Query Single Document

javascript
// Return first matching document
db.users.findOne()

// Single query with condition
db.users.findOne({ name: "John" })

Conditional Queries

Exact Match

javascript
// Query documents where name is "John"
db.users.find({ name: "John" })

// Query multiple conditions (AND)
db.users.find({ name: "John", age: 25 })

Comparison Operators

javascript
// Greater than $gt
db.users.find({ age: { $gt: 25 } })

// Greater than or equal $gte
db.users.find({ age: { $gte: 25 } })

// Less than $lt
db.users.find({ age: { $lt: 30 } })

// Less than or equal $lte
db.users.find({ age: { $lte: 30 } })

// Not equal $ne
db.users.find({ age: { $ne: 25 } })

// Range query
db.users.find({ age: { $gte: 20, $lte: 30 } })

Multiple Value Queries

javascript
// $in - match any value in array
db.users.find({ age: { $in: [20, 25, 30] } })

// $nin - match none of the values in array
db.users.find({ age: { $nin: [20, 25] } })

Logical Operators

AND Conditions

javascript
// Implicit AND
db.users.find({ name: "John", age: 25, city: "New York" })

// Explicit $and
db.users.find({
  $and: [
    { name: "John" },
    { age: 25 }
  ]
})

OR Conditions

javascript
// $or
db.users.find({
  $or: [
    { name: "John" },
    { name: "Jane" }
  ]
})

// Age less than 20 or greater than 60
db.users.find({
  $or: [
    { age: { $lt: 20 } },
    { age: { $gt: 60 } }
  ]
})

NOT Conditions

javascript
// $not
db.users.find({ age: { $not: { $gt: 25 } } })

NOR Conditions

javascript
// $nor - none of the conditions match
db.users.find({
  $nor: [
    { name: "John" },
    { age: 25 }
  ]
})

Array Queries

Query Arrays Containing Elements

javascript
// Query documents where tags contains "tech"
db.articles.find({ tags: "tech" })

// Query arrays containing multiple elements
db.articles.find({ tags: { $all: ["tech", "mongodb"] } })

Query Array Length

javascript
// Query documents where tags has 2 elements
db.articles.find({ tags: { $size: 2 } })

Query Array Specific Position

javascript
// Query where first element of tags is "tech"
db.articles.find({ "tags.0": "tech" })

Nested Document Queries

Dot Notation Queries

javascript
// Query where address.city is "New York"
db.users.find({ "address.city": "New York" })

// Query nested field
db.users.find({ "contacts.phone": "555-0123" })

Query Entire Nested Document

javascript
db.users.find({
  address: {
    city: "New York",
    street: "Main St"
  }
})

Result Processing

Limit Returned Fields

javascript
// Only return name and age fields (_id returned by default)
db.users.find({}, { name: 1, age: 1 })

// Exclude certain fields
db.users.find({}, { password: 0, secret: 0 })

// Only return name field, exclude _id
db.users.find({}, { name: 1, _id: 0 })

Sorting

javascript
// Sort by age ascending
db.users.find().sort({ age: 1 })

// Sort by age descending
db.users.find().sort({ age: -1 })

// Multi-field sorting
db.users.find().sort({ age: -1, name: 1 })

Limiting Results

javascript
// Return only first 5 documents
db.users.find().limit(5)

// Skip first 10, return 5
db.users.find().skip(10).limit(5)

Counting

javascript
// Count all documents
db.users.countDocuments()

// Count with condition
db.users.countDocuments({ age: { $gte: 18 } })

// Estimated count (faster but not precise)
db.users.estimatedDocumentCount()

Advanced Queries

Existence Check

javascript
// Query documents that have email field
db.users.find({ email: { $exists: true } })

// Query documents that don't have phone field
db.users.find({ phone: { $exists: false } })

Type Check

javascript
// Query where age is integer type
db.users.find({ age: { $type: "int" } })

// Query where name is string type
db.users.find({ name: { $type: "string" } })

Regular Expression Queries

javascript
// Fuzzy query - starts with "J"
db.users.find({ name: /^J/ })

// Fuzzy query - contains "ohn"
db.users.find({ name: /ohn/ })

// Case insensitive
db.users.find({ name: /john/i })

// Complex regex
db.users.find({ email: /^[a-z]+@[a-z]+\.[a-z]+$/ })

Query Examples

Comprehensive Query

javascript
// Query active users, age 18-60, sorted by registration time descending
db.users.find({
  status: "active",
  age: { $gte: 18, $lte: 60 }
}, {
  name: 1,
  email: 1,
  age: 1
}).sort({ createdAt: -1 }).limit(20)

Aggregation Query

javascript
// Group by city and count users
db.users.aggregate([
  { $group: { _id: "$city", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

Summary

Key points for querying documents:

  • find() for queries, findOne() returns single result
  • Use comparison operators for conditional queries
  • Use logical operators to combine multiple conditions
  • Use dot notation to query nested documents
  • Use projection to control returned fields

In the next chapter, we will learn about MongoDB Update Document.

Content is for learning and research only.