Implementing MongoDB exists and ne?

The $exists operator checks whether a field exists in a document, while $ne (not equal) filters documents where a field value does not match the specified value. Combining both operators helps find documents with existing fields that contain meaningful data.

Syntax

// $exists operator
db.collection.find({ "fieldName": { "$exists": true/false } });

// $ne operator  
db.collection.find({ "fieldName": { "$ne": "value" } });

// Combined usage
db.collection.find({
    "$and": [
        { "fieldName": { "$exists": true } },
        { "fieldName": { "$ne": "unwantedValue" } }
    ]
});

Sample Data

db.existsDemo.insertMany([
    { "Name": "Chris", "Age": 21 },
    { "Name": "", "Age": null },
    { "Name": null, "Age": 24 },
    { "Age": 23 }
]);

Display All Documents

db.existsDemo.find().pretty();
{
   "_id" : ObjectId("5cd7c3916d78f205348bc650"),
   "Name" : "Chris",
   "Age" : 21
}
{ "_id" : ObjectId("5cd7c39a6d78f205348bc651"), "Name" : "", "Age" : null }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }
{ "_id" : ObjectId("5cd7c3c36d78f205348bc653"), "Age" : 23 }

Example: Find Documents with Non-Empty Name Field

Find documents where the "Name" field exists and is not an empty string ?

db.existsDemo.find({
    "$and": [
        { "Name": { "$exists": true } },
        { "Name": { "$ne": "" } }
    ]
});
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }

Key Points

  • $exists: true matches documents where the field is present, even if the value is null
  • $exists: false matches documents where the field is completely missing
  • $ne matches all values except the specified one, including null
  • Combining both operators helps filter for fields with meaningful non-empty values

Conclusion

Use $exists and $ne together to find documents with existing fields that contain meaningful data. This combination is particularly useful for filtering out empty strings, null values, or missing fields in query results.

Updated on: 2026-03-15T01:19:39+05:30

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements