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
How to query MongoDB using the $ne operator?
To query MongoDB using the $ne operator, use it to find documents where a field is not equal to a specified value. The $ne operator excludes documents that match the given value.
Syntax
db.collection.find({fieldName: {$ne: value}});
Create Sample Data
Let us create a collection with student documents ?
db.notEqualToDemo.insertMany([
{"StudentName": "Larry", "StudentMathMarks": 68},
{"StudentName": "Chris", "StudentMathMarks": 88},
{"StudentName": "David", "StudentMathMarks": 45},
{"StudentName": "Carol", "StudentMathMarks": 69}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cbd3a6bde8cc557214c0ded"),
ObjectId("5cbd3a79de8cc557214c0dee"),
ObjectId("5cbd3a89de8cc557214c0def"),
ObjectId("5cbd3a97de8cc557214c0df0")
]
}
Display All Documents
db.notEqualToDemo.find().pretty();
{
"_id": ObjectId("5cbd3a6bde8cc557214c0ded"),
"StudentName": "Larry",
"StudentMathMarks": 68
}
{
"_id": ObjectId("5cbd3a79de8cc557214c0dee"),
"StudentName": "Chris",
"StudentMathMarks": 88
}
{
"_id": ObjectId("5cbd3a89de8cc557214c0def"),
"StudentName": "David",
"StudentMathMarks": 45
}
{
"_id": ObjectId("5cbd3a97de8cc557214c0df0"),
"StudentName": "Carol",
"StudentMathMarks": 69
}
Example: Using $ne Operator
Find all students whose math marks are not equal to 88 ?
db.notEqualToDemo.find({StudentMathMarks: {$ne: 88}}).pretty();
{
"_id": ObjectId("5cbd3a6bde8cc557214c0ded"),
"StudentName": "Larry",
"StudentMathMarks": 68
}
{
"_id": ObjectId("5cbd3a89de8cc557214c0def"),
"StudentName": "David",
"StudentMathMarks": 45
}
{
"_id": ObjectId("5cbd3a97de8cc557214c0df0"),
"StudentName": "Carol",
"StudentMathMarks": 69
}
Key Points
-
$nereturns documents where the field value does not match the specified value. - Documents with the missing field are also included in the result.
- Works with all data types: numbers, strings, booleans, dates, etc.
Conclusion
The $ne operator is essential for exclusion queries in MongoDB. It selects all documents where a field is not equal to the specified value, making it useful for filtering out unwanted records.
Advertisements
