0
0
MongoDBquery~5 mins

$ne for not equal in MongoDB

Choose your learning style9 modes available
Introduction

We use $ne to find items that do NOT match a certain value. It helps us exclude things we don't want.

Finding all users except those from a specific city.
Getting products that are not in a certain category.
Listing orders that are not completed.
Showing employees who are not in a particular department.
Syntax
MongoDB
{ field: { $ne: value } }

This means: find documents where field is NOT equal to value.

You can use $ne with any data type like numbers, strings, or dates.

Examples
Finds documents where the age is NOT 30.
MongoDB
{ age: { $ne: 30 } }
Finds documents where status is NOT "completed".
MongoDB
{ status: { $ne: "completed" } }
Finds documents where category is NOT "electronics".
MongoDB
{ category: { $ne: "electronics" } }
Sample Program

This query finds all orders where the status is NOT "shipped".

MongoDB
db.orders.find({ status: { $ne: "shipped" } })
OutputSuccess
Important Notes

If the field does not exist in a document, that document will be included because it is considered not equal to the value.

You can combine $ne with other conditions for more complex queries.

Summary

$ne helps find documents where a field is NOT equal to a value.

It works with many data types like numbers and strings.

Useful to exclude unwanted data in your search.