MongoDB Conditional Queries: Examples from Simple to Complex Queries

In MongoDB, conditional queries are the core operation for filtering data from collections. By specifying different conditions, you can precisely retrieve the documents that meet your requirements. This article will explain MongoDB’s conditional query methods with specific examples, starting from simple to complex, suitable for beginners to quickly get started.

1. Prepare Sample Data

For easy demonstration, we assume a collection named users containing the following documents (which can be understood as a user information table):

{
  "_id": 1,
  "name": "Alice",
  "age": 25,
  "hobbies": ["reading", "hiking"],
  "address": { "city": "Beijing", "country": "China" }
},
{
  "_id": 2,
  "name": "Bob",
  "age": 30,
  "hobbies": ["gaming", "coding"],
  "address": { "city": "Shanghai", "country": "China" }
},
{
  "_id": 3,
  "name": "Charlie",
  "age": 22,
  "hobbies": ["music", "sports"],
  "address": { "city": "Guangzhou", "country": "China" }
},
{
  "_id": 4,
  "name": "David",
  "age": 35,
  "hobbies": ["travel", "photography"],
  "address": { "city": "Chengdu", "country": "China" }
}

2. Basic Conditional Queries (Simplest “Equal” Condition)

In MongoDB, conditional queries are implemented through the find() method, where conditions are written in the form of “key-value pairs” in the query document. The most basic condition is equality, i.e., querying documents where a field equals a specified value.

Example 1: Query users aged 25

db.users.find({ age: 25 })
  • Explanation: { age: 25 } is the query condition, meaning “the age field equals 25”.
  • Result: Returns the document with _id 1 (Alice’s information).

Example 2: Query users in “Shanghai”

db.users.find({ "address.city": "Shanghai" })
  • Explanation: address.city is the dot notation for nested fields (address is the parent document, city is the child field), meaning query documents where the city in the address is “Shanghai”.
  • Result: Returns the document with _id 2 (Bob’s information).

3. Comparison Operators (Greater Than, Less Than, Not Equal, etc.)

MongoDB supports multiple comparison operators for more flexible conditional filtering. Common ones include:
- $gt: Greater Than
- $lt: Less Than
- $gte: Greater Than or Equal
- $lte: Less Than or Equal
- $ne: Not Equal

Example 3: Query users older than 25

db.users.find({ age: { $gt: 25 } })
  • Explanation: { age: { $gt: 25 } } means “the age field is greater than 25”.
  • Result: Returns documents with _id 2 (Bob, 30 years old) and 4 (David, 35 years old).

Example 4: Query users aged between 22 and 30 (inclusive)

db.users.find({ age: { $gte: 22, $lte: 30 } })
  • Explanation: The condition is an object containing $gte (greater than or equal) and $lte (less than or equal), indicating the age range is between 22 and 30.
  • Result: Returns documents with _id 1 (25 years old), 2 (30 years old), and 3 (22 years old).

Example 5: Query users whose name is not “Bob”

db.users.find({ name: { $ne: "Bob" } })
  • Explanation: $ne means “not equal”, i.e., exclude documents with the name “Bob”.
  • Result: Returns documents with _id 1, 3, and 4.

4. Logical Operators (AND, OR, NOT)

When combining multiple conditions, MongoDB provides logical operators $and, $or, $not.

Example 6: Query users older than 25 and from “China” (AND condition)

db.users.find({ 
  age: { $gt: 25 }, 
  "address.country": "China" 
})
  • Explanation: Multiple conditions are directly written in the query document. MongoDB defaults to an AND relationship, meaning both “age > 25” and “country is China” must be satisfied.
  • Result: Returns documents with _id 2 (Bob, 30 years old, China) and 4 (David, 35 years old, China).

Example 7: Query users aged 25 or from “Beijing” (OR condition)

db.users.find({ 
  $or: [
    { age: 25 }, 
    { "address.city": "Beijing" }
  ] 
})
  • Explanation: $or requires conditions to be placed in an array, where each element is a condition object. Any one of the conditions can be satisfied.
  • Result: Returns the document with _id 1 (Alice, 25 years old) and the document with _id 1 (Beijing).

Example 8: Query users not older than 30 and whose hobbies do not include “gaming” (NOT condition)

db.users.find({ 
  age: { $not: { $gt: 30 } }, // Age ≤ 30
  hobbies: { $ne: "gaming" }  // Hobbies not equal to "gaming"
})
  • Explanation: $not is used to negate a condition. Here, it negates $gt: 30 (i.e., age ≤ 30), while excluding users whose hobbies include “gaming”.
  • Result: Returns documents with _id 1 (Alice, 25 years old, hobbies do not include gaming) and 3 (Charlie, 22 years old, hobbies do not include gaming).

5. Array Queries (Handling Array Fields)

If a document contains an array type (e.g., hobbies), MongoDB supports array-related conditional queries for common scenarios:
- Array contains a specific element
- Array length equals a specified value
- Elements in the array meet specific conditions

Example 9: Query users whose hobbies include “reading”

db.users.find({ hobbies: "reading" })
  • Explanation: Directly writing an array element as a condition. MongoDB defaults to matching documents containing that element in the array (equivalent to the $in operation).
  • Result: Returns the document with _id 1 (Alice’s information, hobbies include reading).

Example 10: Query users whose hobbies include “reading” or “travel”

db.users.find({ hobbies: { $in: ["reading", "travel"] } })
  • Explanation: $in specifies a list of values; the document matches if the array contains any element from the list.
  • Result: Returns documents with _id 1 (Alice, includes reading) and 4 (David, includes travel).

Example 11: Query users with a hobby array of length 2

db.users.find({ hobbies: { $size: 2 } })
  • Explanation: $size specifies the array length, here meaning the number of elements is 2.
  • Result: Returns documents with _id 1 (Alice, 2 hobbies) and 2 (Bob, 2 hobbies).

6. String Matching Queries (Regular Expressions)

Use $regex for fuzzy string matching, supporting regular expression syntax.

Example 12: Query users whose names start with “A”

db.users.find({ name: { $regex: /^A/ } })
  • Explanation: /^A/ is a regular expression meaning “starts with A”. $regex specifies the matching rule.
  • Result: Returns the document with _id 1 (Alice).

Example 13: Query users whose names contain “li” (case-insensitive)

db.users.find({ name: { $regex: /li/i } })
  • Explanation: The i in /li/i indicates case insensitivity, and li matches strings containing “li”.
  • Result: If there are users named “Alex” or “Li”, they will be matched. No such users exist in the sample data.

7. Summary

MongoDB conditional queries can achieve simple to complex filtering needs by combining different condition operators and logical operators. Key points:
1. Basic Query: Directly match by field name = value (equality condition).
2. Comparison Operators: Use $gt/$lt etc. for range queries.
3. Logical Operators: $and (default), $or, $not to combine multiple conditions.
4. Array Queries: $in, $size etc. handle array element matching.
5. String Matching: $regex supports regular expression fuzzy queries.

By practicing the above examples, you can gradually master the core logic of MongoDB conditional queries to handle most data filtering scenarios.

Exercises

Try querying with the following conditions to verify your understanding:
1. Query users younger than 30 and from “Guangzhou”.
2. Query users whose hobbies include “coding” or “photography”.
3. Query users whose names start with “C” and have an even age.

(Answers can be verified by executing the corresponding query statements in the MongoDB client.)

Xiaoye