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
MongoDB inverse of query to return all items except specific documents?
To get documents except some specific documents, use $nor along with $and. The $nor operator returns documents that do not match any of the specified conditions, making it perfect for inverse queries.
Syntax
db.collection.find({
$nor: [
{ $and: [{ field1: value1 }, { field2: value2 }] }
]
});
Sample Data
Let us first create a collection with sample student documents ?
db.demo1.insertMany([
{ "StudentName": "Chris", "StudentMarks": 38 },
{ "StudentName": "David", "StudentMarks": 78 },
{ "StudentName": "Mike", "StudentMarks": 96 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e08a4f025ddae1f53b62216"),
ObjectId("5e08a4f725ddae1f53b62217"),
ObjectId("5e08a4fd25ddae1f53b62218")
]
}
Display All Documents
db.demo1.find().pretty();
{
"_id": ObjectId("5e08a4f025ddae1f53b62216"),
"StudentName": "Chris",
"StudentMarks": 38
}
{
"_id": ObjectId("5e08a4f725ddae1f53b62217"),
"StudentName": "David",
"StudentMarks": 78
}
{
"_id": ObjectId("5e08a4fd25ddae1f53b62218"),
"StudentName": "Mike",
"StudentMarks": 96
}
Example: Exclude Specific Document
Here is the query to get all documents except David with marks 78 ?
db.demo1.find({
$nor: [
{ $and: [{ 'StudentName': 'David' }, { 'StudentMarks': 78 }] }
]
});
{ "_id": ObjectId("5e08a4f025ddae1f53b62216"), "StudentName": "Chris", "StudentMarks": 38 }
{ "_id": ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName": "Mike", "StudentMarks": 96 }
Alternative Method: Using $ne
For simple exclusions, you can also use $ne (not equal) ?
db.demo1.find({ "StudentName": { $ne: "David" } });
Conclusion
Use $nor with $and for complex inverse queries to exclude documents matching multiple conditions. For simple exclusions, $ne provides a cleaner alternative.
Advertisements
