Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find records in MongoDB that does NOT match a condition?
To find records that do not match a condition in MongoDB, use the $ne (not equal) operator. This operator excludes documents where the specified field equals the given value.
Syntax
db.collection.find({ "fieldName": { "$ne": "value" } })
Sample Data
Let us create a collection with sample documents:
db.demo148.insertMany([
{ "Message": "Hello" },
{ "Message": "Good" },
{ "Message": "Bye" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e32fb37fdf09dd6d08539c0"),
ObjectId("5e32fb3efdf09dd6d08539c1"),
ObjectId("5e32fb42fdf09dd6d08539c2")
]
}
Display all documents from the collection:
db.demo148.find()
{ "_id": ObjectId("5e32fb37fdf09dd6d08539c0"), "Message": "Hello" }
{ "_id": ObjectId("5e32fb3efdf09dd6d08539c1"), "Message": "Good" }
{ "_id": ObjectId("5e32fb42fdf09dd6d08539c2"), "Message": "Bye" }
Example: Find Records NOT Equal to "Good"
Find all documents where Message is not equal to "Good":
db.demo148.find({ "Message": { "$ne": "Good" } })
{ "_id": ObjectId("5e32fb37fdf09dd6d08539c0"), "Message": "Hello" }
{ "_id": ObjectId("5e32fb42fdf09dd6d08539c2"), "Message": "Bye" }
Key Points
-
$neexcludes documents where the field exactly matches the specified value - Documents with missing fields are included in results (null values don't equal the specified value)
- Case-sensitive matching applies for string comparisons
Conclusion
The $ne operator efficiently filters out documents that match a specific condition. Use it to exclude unwanted records and find all documents that don't meet certain criteria.
Advertisements
