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
Get all the MongoDB documents but not the ones with two given criteria's?
To get all MongoDB documents except those matching specific criteria, use the $ne operator for a single criterion or the $nin operator for multiple criteria exclusion.
Syntax
Single Criterion Exclusion:
db.collection.find({field: {$ne: "value"}});
Multiple Criteria Exclusion:
db.collection.find({field: {$nin: ["value1", "value2"]}});
Sample Data
Let us create a collection with sample documents ?
db.findAllExceptFromOneOrtwoDemo.insertMany([
{"StudentName": "Larry", "StudentSubjectName": "Java"},
{"StudentName": "Chris", "StudentSubjectName": "C++"},
{"StudentName": "Robert", "StudentSubjectName": "C"},
{"StudentName": "David", "StudentSubjectName": "Python"}
]);
Display all documents in the collection ?
db.findAllExceptFromOneOrtwoDemo.find();
{
"_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
"StudentName": "Larry",
"StudentSubjectName": "Java"
}
{
"_id": ObjectId("5c993d8f330fd0aa0d2fe4d3"),
"StudentName": "Chris",
"StudentSubjectName": "C++"
}
{
"_id": ObjectId("5c993d99330fd0aa0d2fe4d4"),
"StudentName": "Robert",
"StudentSubjectName": "C"
}
{
"_id": ObjectId("5c993da4330fd0aa0d2fe4d5"),
"StudentName": "David",
"StudentSubjectName": "Python"
}
Case 1: Exclude Single Criterion Using $ne
Find all documents except those with StudentSubjectName as "C" ?
db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName: {$ne: "C"}});
{
"_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
"StudentName": "Larry",
"StudentSubjectName": "Java"
}
{
"_id": ObjectId("5c993d8f330fd0aa0d2fe4d3"),
"StudentName": "Chris",
"StudentSubjectName": "C++"
}
{
"_id": ObjectId("5c993da4330fd0aa0d2fe4d5"),
"StudentName": "David",
"StudentSubjectName": "Python"
}
Case 2: Exclude Multiple Criteria Using $nin
Find all documents except those with StudentSubjectName as "C++" or "Python" ?
db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName: {$nin: ["C++", "Python"]}});
{
"_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
"StudentName": "Larry",
"StudentSubjectName": "Java"
}
{
"_id": ObjectId("5c993d99330fd0aa0d2fe4d4"),
"StudentName": "Robert",
"StudentSubjectName": "C"
}
Key Points
-
$neexcludes documents where the field equals the specified value -
$ninexcludes documents where the field matches any value in the array - Both operators return all documents that do not match the specified criteria
Conclusion
Use $ne for single value exclusion and $nin for multiple value exclusion. These operators effectively filter out unwanted documents while returning all others that meet your query requirements.
Advertisements
