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
Search by property name for any document with that property in MongoDB?
To search for documents that contain a specific property in MongoDB, use the $ne operator with a null value. This will return all documents where the property exists and is not null.
Syntax
db.collection.find({ propertyName: { $ne: null } })
Sample Data
db.searchByPropertyName.insertMany([
{ "FirstName": "Larry", "Age": 23 },
{ "FirstName": null, "Age": 21 },
{ "FirstName": "John", "Age": 22 },
{ "FirstName": null, "Age": 25 },
{ "FirstName": "David", "Age": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cbaf7af7219729fde21ddb5"),
ObjectId("5cbaf7b97219729fde21ddb6"),
ObjectId("5cbaf7c57219729fde21ddb7"),
ObjectId("5cbaf7d07219729fde21ddb8"),
ObjectId("5cbaf7df7219729fde21ddb9")
]
}
View All Documents
db.searchByPropertyName.find()
{
"_id": ObjectId("5cbaf7af7219729fde21ddb5"),
"FirstName": "Larry",
"Age": 23
}
{
"_id": ObjectId("5cbaf7b97219729fde21ddb6"),
"FirstName": null,
"Age": 21
}
{
"_id": ObjectId("5cbaf7c57219729fde21ddb7"),
"FirstName": "John",
"Age": 22
}
{
"_id": ObjectId("5cbaf7d07219729fde21ddb8"),
"FirstName": null,
"Age": 25
}
{
"_id": ObjectId("5cbaf7df7219729fde21ddb9"),
"FirstName": "David",
"Age": 20
}
Search by Property Name
Find all documents where FirstName property exists and is not null ?
db.searchByPropertyName.find({ FirstName: { $ne: null } })
{
"_id": ObjectId("5cbaf7af7219729fde21ddb5"),
"FirstName": "Larry",
"Age": 23
}
{
"_id": ObjectId("5cbaf7c57219729fde21ddb7"),
"FirstName": "John",
"Age": 22
}
{
"_id": ObjectId("5cbaf7df7219729fde21ddb9"),
"FirstName": "David",
"Age": 20
}
Alternative: Using $exists
To find documents where a property exists regardless of its value ?
db.searchByPropertyName.find({ FirstName: { $exists: true } })
Conclusion
Use { propertyName: { $ne: null } } to find documents with non-null property values, or { propertyName: { $exists: true } } to find documents where the property exists regardless of value.
Advertisements
