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
Can we use NOT and AND together in MongoDB?
Yes, we can use NOT and AND together in MongoDB. MongoDB doesn't have direct NOT and AND operators, but we achieve this using $or and $ne operators following De Morgan's law: NOT (X AND Y) = NOT X OR NOT Y.
Syntax
db.collection.find({
"$or": [
{"field1": {"$ne": "value1"}},
{"field2": {"$ne": "value2"}}
]
});
Sample Data
db.NotAndDemo.insertMany([
{"StudentName": "John", "StudentCountryName": "US"},
{"StudentName": "John", "StudentCountryName": "UK"},
{"StudentName": "David", "StudentCountryName": "AUS"},
{"StudentName": "Chris", "StudentCountryName": "UK"},
{"StudentName": "Chris", "StudentCountryName": "US"}
]);
Example: NOT (Chris AND US)
Find all students who are NOT (both Chris from US) ?
db.NotAndDemo.find({
"$or": [
{"StudentName": {"$ne": "Chris"}},
{"StudentCountryName": {"$ne": "US"}}
]
});
{
"_id": ObjectId("..."),
"StudentName": "John",
"StudentCountryName": "US"
}
{
"_id": ObjectId("..."),
"StudentName": "John",
"StudentCountryName": "UK"
}
{
"_id": ObjectId("..."),
"StudentName": "David",
"StudentCountryName": "AUS"
}
{
"_id": ObjectId("..."),
"StudentName": "Chris",
"StudentCountryName": "UK"
}
How It Works
The query excludes documents where both conditions are true (StudentName="Chris" AND StudentCountryName="US"). It returns documents where at least one condition is false:
- Students not named "Chris" (regardless of country)
- Students not from "US" (regardless of name)
Conclusion
Use $or with $ne operators to implement NOT AND logic in MongoDB. This follows De Morgan's law where NOT (A AND B) equals (NOT A OR NOT B).
Advertisements
