MongoDB $ne Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $ne?

$ne is MongoDB’s not-equal operator. In aggregation it compares two expressions and returns true or false. In query filters it keeps documents where a field is not equal to a value (and usually includes documents missing that field).

Remember
$ne = not equal? → true / false

Aggregation:
  { $ne: [ <a>, <b> ] }

Query / $match:
  { field: { $ne: value } }
  // no shorthand (unlike $eq)

$ne(["$status", "closed"]) → true or false
query $ne also matches missing fields
UsePrefer
True/false not-equal$ne
Equality$eq
Exclude several values$nin

How to Use $ne in MongoDB

Pick filter mode or boolean mode, then compare a field to a value (or two fields).

  1. To filter documents, use $match (or find()) with { field: { $ne: value } }.
  2. To add a boolean, use $project / $addFields with { $ne: [a, b] }.
  3. Remember: query $ne often matches missing fields too.
  4. Use $nin when excluding more than one value.
PieceRequired?Role
$neYesNot-equal test
Two expressions (agg)YesValues to compare → boolean
Field + value (query)YesKeep non-matching documents

Pseudocode

Pseudocode
// Aggregation — boolean
for each document:
    a = evaluate(expression1)
    b = evaluate(expression2)
    if a and b are equivalent (value + type):
        result = false
    else:
        result = true
    emit { ..., field: result }

// Query — filter
keep document if field value is not equal to target
             (usually includes missing field)

Cheat Sheet

Keep these facts handy while writing not-equal checks.

TopicDetail
Agg syntax{ $ne: [ <a>, <b> ] }
Query syntax{ field: { $ne: value } }
ShorthandNone (must use $ne)
Returns (agg)true or false
TypesBSON rules (no loose coercion)
Query + missingMissing field usually matches
Sample$ne(["$qty", 250])

Live Preview

Watch $ne test whether a status is not "closed".

Simulates { $ne: ["$status", "closed"] } (same idea as the mongosh examples below).

Result
status = "open"
$ne([status, "closed"]) → true

{ status: "open", notClosed: true }

Worked Walkthrough — Not Closed?

Same question for every order: is status not equal to "closed"?

Calculation
Target to exclude = "closed"

status "open"    → not equal → true
status "pending" → not equal → true
status "closed"  → equal     → false

Aggregation field:
  notClosed: { $ne: ["$status", "closed"] }

Filter form (drops closed):
  { $match: { status: { $ne: "closed" } } }

MongoDB Examples

We store inventory rows, add a boolean with aggregation $ne, then filter with query $ne. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine a tiny inventory collection. One item has quantity 250; the others do not.

mongosh
db.inventory.insertMany([
  { _id: 1, item: "abc1", qty: 300 },
  { _id: 2, item: "abc2", qty: 200 },
  { _id: 3, item: "xyz1", qty: 250 },
  { _id: 4, item: "VWZ1", qty: 300 },
  { _id: 5, item: "VWZ2", qty: 180 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps five documents. Run find() to see them:

mongosh
db.inventory.find()

Read one document like this:

Field in MongoDBValue (doc 3)Plain English
item"xyz1"Product code
qty250Stock quantity

How It Works

  1. Insert once. insertMany adds five inventory documents.
  2. qty is a number. We will ask “is qty not 250?” next.
  3. find() shows the same shape. Ready for $ne.

Example 2 — Boolean with $ne

Goal: add a boolean that is true when qty is not 250.

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      qty: 1,
      qtyNe250: { $ne: ["$qty", 250] },
      _id: 0
    }
  }
]);

How It Works

  1. Compare two values. { $ne: ["$qty", 250] } means qty ≠ 250.
  2. Equal → false. Only xyz1 has qty: 250, so qtyNe250 is false.
  3. Not equal → true. All other rows return true.
  4. Keeps every document. Aggregation $ne adds a flag; it does not drop rows.

Example 3 — Filter with $match

Same idea as a filter: keep only documents where qty is not 250.

mongosh
db.inventory.aggregate([
  { $match: { qty: { $ne: 250 } } }
]);

// same idea with find():
// db.inventory.find({ qty: { $ne: 250 } });

How It Works

  1. Query form. { qty: { $ne: 250 } } keeps rows where qty is not 250.
  2. Dropped. xyz1 (qty 250) is removed from the result.
  3. No shorthand. Unlike $eq, you cannot write { qty: 250 } for not-equal—you need $ne.
  4. Missing fields. If a document had no qty, query $ne would usually keep it too.

Edge Cases & Pitfalls

Check these before using $ne in production pipelines.

missing

Query $ne matches missing fields

That can surprise you. Combine with $exists when you only want documents that have the field.

type

Types matter

"250" (string) is not equal to 250 (number), so $ne between them is true. Keep types consistent.

selectivity

$ne is often not selective

Excluding one value can still match most of a collection. Prefer positive filters when you can, or add other selective conditions.

list

Many values → use $nin

Chaining several $ne checks is awkward. Use $nin for a list of excluded values.

Performance Notes

ApproachCostBest for
Agg $ne booleanPer-document compareFlags / conditional fields
Query $neOften broad match setExclude one value
$ne + other filtersUsually betterNarrow then exclude

Query $ne often matches a large share of an index, so it may not beat a collection scan. Pair it with selective predicates in $match when possible.

Key Takeaways

  • Role: not equal → true/false or filter.
  • Agg: { $ne: [a, b] }.
  • Query: { field: { $ne: value } } (no shorthand).
  • Watch missing fields in query filters.

One line: $ne answers “are these different?”—as a boolean, or as a filter that keeps non-matches.

Frequently Asked Questions

$ne checks whether two values are not equal. In aggregation expressions it returns true or false. In query filters it matches documents where a field is not equal to a value—including documents that are missing the field.
Aggregation: { $ne: [ <expression1>, <expression2> ] }. Query filter: { field: { $ne: value } }. Unlike $eq, query $ne has no shorthand—you must write the operator form.
Yes. { field: { $ne: value } } matches documents that do not contain the field, and documents where the field is null (unless you add $exists / type checks).
$ne excludes one value. $nin excludes any value in a list. Use $nin when you need to skip several values at once.
Yes. $ne uses BSON comparison rules. The string "10" is not equal to the number 10, so $ne between them is true.
In aggregation, a missing field is treated as distinct from null. Two missing fields are considered equivalent. A missing field compared to null is not equal.

Next: $nin

Exclude documents whose field matches any value in a list.

$nin tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful