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 query to determine if a specific value does not exist?
To determine if a specific value does not exist, use the $ne (not equal) operator in MongoDB. This operator matches documents where the field value does not equal the specified value.
Syntax
db.collection.find({ "field": { "$ne": "value" } })
Sample Data
db.demo206.insertMany([
{
"ClientDetails": [
{
"Name": "Chris",
"Age": 28,
"CountryName": "US"
}
]
},
{
"ClientDetails": [
{
"Name": "David",
"Age": 29,
"CountryName": "UK"
}
]
},
{
"ClientDetails": [
{
"Name": "Bob",
"Age": 31,
"CountryName": "US"
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3d8bd403d395bdc21346ee"),
ObjectId("5e3d8bd403d395bdc21346ef"),
ObjectId("5e3d8bd503d395bdc21346f0")
]
}
Example: Find Documents Where CountryName is Not "US"
Let's find all documents where the CountryName is not "US" ?
db.demo206.find({"ClientDetails.CountryName": {"$ne": "US"}});
{
"_id": ObjectId("5e3d8bd403d395bdc21346ef"),
"ClientDetails": [
{
"Name": "David",
"Age": 29,
"CountryName": "UK"
}
]
}
Key Points
- Use dot notation to access nested array fields like
"ClientDetails.CountryName" -
$nealso matches documents where the field does not exist - Case-sensitive matching applies to string comparisons
Conclusion
The $ne operator effectively filters out documents containing specific values, making it useful for exclusion-based queries. It works with all data types and nested fields using dot notation.
Advertisements
