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
Invert Result of MongoDB Query (Implement Opposite of $and operation)?
To invert the result of a MongoDB query (opposite of $and operation), use $or combined with $ne operators. This applies De Morgan's Law: NOT (A AND B) = (NOT A) OR (NOT B).
Syntax
db.collection.find({
$or: [
{ "field1": { $ne: "value1" } },
{ "field2": { $ne: "value2" } }
]
});
Sample Data
db.demo4.insertMany([
{ uid: 1, "Name": "Chris", "Age": 22 },
{ uid: 2, "Name": "David", "Age": 21 },
{ uid: 3, "Name": "Bob", "Age": 23 },
{ uid: 1, "Name": "Carol", "Age": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Display all documents ?
db.demo4.find();
{ "_id": ObjectId("5e0a1da125ddae1f53b62221"), "uid": 1, "Name": "Chris", "Age": 22 }
{ "_id": ObjectId("5e0a1db025ddae1f53b62222"), "uid": 2, "Name": "David", "Age": 21 }
{ "_id": ObjectId("5e0a1dc225ddae1f53b62223"), "uid": 3, "Name": "Bob", "Age": 23 }
{ "_id": ObjectId("5e0a1dd225ddae1f53b62224"), "uid": 1, "Name": "Carol", "Age": 20 }
Example: Invert $and Query
Instead of finding documents where Name = "Carol" AND Age = 21, find documents where Name ? "Carol" OR Age ? 21 ?
db.demo4.find({
uid: 2,
$or: [
{ "Name": { $ne: "Carol" } },
{ "Age": { $ne: 21 } }
]
});
{ "_id": ObjectId("5e0a1db025ddae1f53b62222"), "uid": 2, "Name": "David", "Age": 21 }
How It Works
The query matches documents where at least one condition is true:
- Name is NOT "Carol" (David ? Carol) ?
- Age is NOT 21 (21 = 21) ?
Since one condition is satisfied, the document is returned.
Conclusion
Use $or with $ne operators to invert $and queries. This follows De Morgan's Law where NOT (A AND B) becomes (NOT A) OR (NOT B), providing the logical opposite of conjunction operations.
Advertisements
