MongoDB $ne Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Comparison

What You’ll Learn

The $ne operator checks whether two values are not equal. Use it in $match to exclude specific values, or in expression stages like $project and $cond to get a true/false result.

01

Not Equal

Exclude matching values.

02

Two Syntax Forms

Query filter vs expression.

03

$match Stage

Filter out unwanted rows.

04

Boolean Output

true or false in $project.

05

Use Cases

Exclusions, validation.

06

Missing Fields

Know inclusion behavior.

Definition and Usage

In MongoDB, the $ne operator tests inequality in two contexts. In a $match stage, { status: { $ne: "archived" } } keeps documents where status is anything other than "archived". In an aggregation expression, { $ne: [ "$role", "admin" ] } returns true or false for each document.

💡
Beginner Tip

Unlike $eq, there is no shorthand for $ne. You must write { field: { $ne: value } } explicitly. Also, query $ne matches documents where the field is missing or null.

📝 Syntax

$ne has two forms depending on where you use it:

Query form (in $match or find filters)

mongosh
{ field: { $ne: <value> } }

Aggregation expression form (in $project, $cond, etc.)

mongosh
{ $ne: [ <expression1>, <expression2> ] }

Syntax Rules

  • Query form — matches documents where the field is not equal to the given value (includes missing/null fields).
  • Expression form — compares two expressions and returns true or false.
  • Both operands must follow BSON comparison rules (no automatic type conversion).
  • Use expression form inside $project, $addFields, $cond, and $filter.
  • For excluding multiple values, use $nin instead.

💡 $ne vs $eq vs $nin

$eq{ status: "active" } or { status: { $eq: "active" } }
$ne{ status: { $ne: "archived" } } (exclude one value)
$nin{ status: { $nin: ["archived", "cancelled"] } } (exclude many values)

⚡ Quick Reference

QuestionAnswer
Operator typeComparison operator (query + expression)
Query syntax{ field: { $ne: value } }
Expression syntax{ $ne: [ expr1, expr2 ] }
Expression outputtrue or false
Missing fieldsQuery $ne matches documents without the field
$match filter
{
  status: { $ne: "archived" }
}

Exclude archived

Expression
{
  $ne: [ "$role", "admin" ]
}

Returns true/false

Field vs field
{
  $ne: [ "$expected", "$actual" ]
}

Detect mismatch

With $exists
{
  status: { $exists: true, $ne: null }
}

Field present, not null

Examples Gallery

Exclude archived orders, filter in find(), add boolean flags, and power conditional logic with $ne.

📚 Exclude a Status Value

Use an orders collection and filter out archived orders with $match.

Sample Input Documents

Suppose you have an orders collection with orderId, customer, and status:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "orderId": "ORD-101", "customer": "Alice", "status": "active" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "orderId": "ORD-102", "customer": "Bob",   "status": "archived" },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "orderId": "ORD-103", "customer": "Carol", "status": "pending" }
]

Example 1 — $ne in a $match Stage

Find orders that are not archived:

mongosh
db.orders.aggregate([
  {
    $match: {
      status: { $ne: "archived" }
    }
  }
])

How It Works

  • Alice (active) and Carol (pending) pass the filter.
  • Bob (archived) is excluded because his status equals the excluded value.
  • Documents without a status field would also match $ne.

📈 Practical Patterns

Use find(), add boolean flags, compare fields, and build conditional labels.

Example 2 — $ne in a find() Query

Exclude cancelled orders outside an aggregation pipeline:

mongosh
db.orders.find({
  status: { $ne: "cancelled" }
})

How It Works

$ne in find() uses the same query form as $match. It is one of the most common ways to exclude a single unwanted value.

Example 3 — Add a Boolean Field with $project

Flag users who are not admins on every document:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      role: 1,
      isNotAdmin: {
        $ne: [ "$role", "admin" ]
      }
    }
  }
])

How It Works

The expression form does not filter documents. It adds true or false to every document based on whether role differs from "admin".

Example 4 — $ne Inside $cond

Label inventory items as “mismatch” when expected and actual counts differ:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      expected: 1,
      actual: 1,
      checkResult: {
        $cond: [
          { $ne: [ "$expected", "$actual" ] },
          "mismatch",
          "ok"
        ]
      }
    }
  }
])

How It Works

When $ne returns true (values differ), $cond outputs "mismatch". When they are equal, it outputs "ok". This is the inverse of an $eq-based check.

Bonus — Exclude null but Require Field to Exist

Combine $exists with $ne when you only want documents with a real value:

mongosh
db.orders.find({
  status: { $exists: true, $ne: null }
})

// Matches documents that HAVE a status field
// and status is not null
// (unlike $ne alone, which also matches missing fields)

How It Works

Plain { status: { $ne: null } } matches documents without status. Adding $exists: true narrows the filter to documents where the field is present and not null.

🚀 Use Cases

  • Status exclusions — hide archived, cancelled, or deleted records from active views.
  • Data validation — flag documents where expected and actual fields differ.
  • Role-based logic — identify non-admin users or non-premium accounts in pipelines.
  • Null filtering — find documents where a field is set to any value other than null.

🧠 How $ne Works

1

MongoDB reads the operands

In $match, it checks a field against an excluded value. In expressions, it evaluates two operands like "$role" and "admin".

Input
2

$ne compares for inequality

MongoDB checks whether the values are not equal using BSON comparison rules. Missing fields count as not equal in query form.

Compare
3

Result is applied in the pipeline

In $match, non-matching documents pass through. In expressions, true or false is stored in the output field.

Output
=

Filtered or flagged documents

You get excluded results or boolean fields ready for validation and conditional logic.

Conclusion

The $ne operator is the go-to tool for excluding a single value in MongoDB queries and for testing inequality in aggregation expressions. It complements $eq and pairs naturally with $cond for mismatch detection.

Remember there is no shorthand for $ne, query form matches missing fields, and $nin is better for excluding multiple values. Next in the series: $nin.

💡 Best Practices

✅ Do

  • Use $ne to exclude a single unwanted value
  • Combine with $exists: true when missing fields should not match
  • Use $nin when excluding multiple values at once
  • Use expression form inside $cond for mismatch labels
  • Keep BSON types consistent (string vs number)

❌ Don’t

  • Assume a shorthand exists for $ne like $eq has
  • Forget that query $ne matches documents without the field
  • Use multiple $ne on the same field (use $nin instead)
  • Confuse expression $ne with query filter syntax
  • Expect automatic type coercion between strings and numbers

Key Takeaways

Knowledge Unlocked

Five things to remember about $ne

Use these points when writing not-equal filters and expressions.

5
Core concepts
📝 02

Two Forms

Query vs expression.

Syntax
🛠 03

No Shorthand

Must use $ne explicitly.

Critical
🔍 04

Missing Fields

Query $ne includes them.

Edge case
📑 05

Use $nin

For multiple exclusions.

Related

❓ Frequently Asked Questions

$ne checks whether two values are not equal. In query filters it matches documents where a field does not equal a value. In aggregation expressions it returns true or false when comparing two expressions.
Query form: { field: { $ne: value } }. Aggregation expression form: { $ne: [ <expression1>, <expression2> ] }. There is no shorthand for $ne in queries — you must use the explicit operator form.
Yes. In query form, { field: { $ne: value } } also matches documents that do not contain the field or where the field is null. Use $exists and $ne together if you need to exclude only exact matches on existing fields.
$ne excludes a single value: { status: { $ne: "archived" } }. $nin excludes any value in an array: { status: { $nin: ["archived", "cancelled"] } }. Use $nin when excluding multiple values.
No. Like $eq, $ne requires strict BSON type matching. Comparing string "10" to number 10 is considered not equal, but both are not equal to each other in the expected sense — always match types consistently.

Continue the Operator Series

Move on to $nin for excluding multiple values, or review $eq for equality checks.

Next: $nin →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful