Must-Know for Beginners: Basic MongoDB Query Syntax

Before we start querying with MongoDB, let’s quickly understand a few core concepts: A Collection is similar to a “table” in relational databases, and a Document is the basic data unit in MongoDB, consisting of key-value pairs (similar to JSON). To perform queries, you first need to ensure you’ve connected to MongoDB and switched to the target database and collection.

1. Connection and Basic Query Preparation

Assuming you have installed MongoDB and started the service, open a command-line tool (like Terminal or Command Prompt) and enter mongo to access the MongoDB Shell. Execute the following commands to switch to the test database and create a sample collection users (similar to a “table”):

// Switch to the test database
use test

// Insert test data (assuming we have a user collection with name, age, hobbies fields)
db.users.insertMany([
  { name: "Alice", age: 25, hobbies: ["reading", "gaming"] },
  { name: "Bob", age: 30, hobbies: ["sports"] },
  { name: "Charlie", age: 22, hobbies: ["reading", "coding"] },
  { name: "David", age: 18, hobbies: ["reading"] }
])

2. Basic Query: The find() Method

find() is MongoDB’s most core query method for retrieving documents from a collection. Syntax:
db.collection.find(query, projection)
- Query Condition: Specifies fields to match (omitting it returns all documents).
- Projection Options: Specifies which fields to return (0 = exclude, 1 = include; all fields are returned by default).

1. Query All Documents

To view all users in the collection, call find() directly:

// Return all user documents
db.users.find()

// Format output with pretty() (to avoid long, unreadable results)
db.users.find().pretty()

3. Conditional Queries: Matching Specific Documents

MongoDB uses “key-value pair” condition objects to define matching rules. For example, to query users with name equal to “Alice”:

// Match documents where name equals "Alice"
db.users.find({ name: "Alice" })

Common Comparison Operators

MongoDB supports various comparison conditions. Here are the most commonly used:

Operator Meaning Example Description
$eq Equal {age: 25} Age equals 25
$gt Greater than {age: {$gt: 20}} Age > 20
$lt Less than {age: {$lt: 30}} Age < 30
$gte Greater than or equal {age: {$gte: 18}} Age ≥ 18
$lte Less than or equal {age: {$lte: 30}} Age ≤ 30
$ne Not equal {age: {$ne: 25}} Age ≠ 25

Example: Query users aged between 20 and 30 ($gt + $lt):

db.users.find({ 
  age: { $gt: 20, $lt: 30 }  // Conditions are combined with AND by default
})

4. Logical Queries: Combining Conditions

MongoDB supports logical operators like $and (default), $or, and $not to combine multiple conditions.

1. $and (Default)

Use $and when multiple conditions must be met simultaneously. However, MongoDB implicitly includes $and, so you don’t need to write it explicitly:

// Query users with age > 20 and name containing "Bob"
db.users.find({ 
  age: { $gt: 20 }, 
  name: { $regex: "Bob" }  // Regular expression match (see below)
})

2. $or (Match Any Condition)

Use $or if only one of the multiple conditions needs to be satisfied:

// Query users with age > 30 OR name is "Alice"
db.users.find({ 
  $or: [
    { age: { $gt: 30 } }, 
    { name: "Alice" }
  ]
})

3. $not (Negation)

Negate a condition, e.g., query users “not older than 20”:

db.users.find({ 
  age: { $not: { $gt: 20 } }  // Equivalent to age ≤ 20
})

5. String and Array Queries

Use regular expressions or $regex for fuzzy matching:

// Match users whose name starts with "A"
db.users.find({ name: /^A/ })  // Regular expression syntax

// Equivalent to
db.users.find({ name: { $regex: "^A" } })

2. Array Queries

For array fields (e.g., hobbies), use operators like $in (contains any element) or $size (array length):

Operator Meaning Example Description
$in Contains any element { hobbies: { $in: ["reading"] } } Hobbies include “reading”
$size Array length equals { hobbies: { $size: 2 } } Hobbies array has 2 elements
$elemMatch Array element matches { hobbies: { $elemMatch: { $eq: "reading" } } } Hobbies array contains “reading”

Example: Query users with hobbies containing “reading” and an array length of 2:

db.users.find({ 
  hobbies: { 
    $in: ["reading"],    // Includes "reading"
    $size: 2             // Array length is 2
  } 
})

6. Projection Queries: Return Only Specific Fields

By default, queries return all fields in a document. To retrieve only specific fields, use the projection parameter (second argument):
- 1 = include the field, 0 = exclude the field (the _id field is returned by default; explicitly set to 0 to exclude it).

Example: Return only name and age (exclude _id):

db.users.find(
  { age: { $gt: 20 } },  // Query condition
  { name: 1, age: 1, _id: 0 }  // Projection: include name, age; exclude _id
)

7. Sorting and Limiting Results

1. Sorting (sort())

Sort by a field with 1 for ascending order and -1 for descending order:

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

2. Limiting Results (limit() and skip())

  • limit(n): Returns up to n results.
  • skip(n): Skips the first n results (commonly used for pagination).

Example: Return the first 2 results:

db.users.find().limit(2)

Pagination Example: Skip the first 2 results and return the next 2:

db.users.find().skip(2).limit(2)

8. Statistics and Deduplication

1. Counting Documents (countDocuments())

// Count users with age > 20
db.users.countDocuments({ age: { $gt: 20 } })

2. Deduplication Query (distinct())

Returns all unique values for a specified field:

// Get all unique hobbies
db.users.distinct("hobbies")

9. Notes

  1. Condition Order: MongoDB automatically optimizes query order; no manual adjustment is needed.
  2. Performance Considerations: Avoid using skip(n) for large-data pagination. Instead, use a cursor based on _id (e.g., _id > lastId).
  3. Avoid Full Table Scans: Always include indexed fields (e.g., age, name) in queries to significantly improve speed.

10. Summary and Practice

The core of MongoDB query syntax is “conditions + projection + sorting + limiting”. Follow these steps to get started:
1. Define the query conditions (equality, comparisons, logic, regex, etc.).
2. Select the fields to return (projection).
3. Use sort() to order results and limit() to restrict the number of results.

Suggested Practice: Create a test collection with mixed field types (strings, arrays, numbers) and try these queries:
- Query users with age 25 and return only name.
- Find users with “coding” in hobbies and age < 25.
- Return the top 3 results sorted by age in descending order.

Through practical operations, you’ll quickly master MongoDB query logic!

Xiaoye