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.

Updated on: 2026-03-15T00:49:35+05:30

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements