MongoDB query for exact match

For exact match queries in MongoDB, you can combine the $exists operator with field conditions to ensure precise matching, especially when dealing with fields that could contain either single values or arrays.

Syntax

db.collection.find({
    $and: [
        {"field.0": {$exists: false}},
        {"field": "exactValue"}
    ]
});

Sample Data

db.demo290.insertMany([
    {"ListOfName": "Chris"},
    {"ListOfName": ["Chris", "David"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e4c0c9e5d93261e4bc9ea2d"),
        ObjectId("5e4c0cb05d93261e4bc9ea2e")
    ]
}

Display all documents from the collection ?

db.demo290.find();
{ "_id": ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName": "Chris" }
{ "_id": ObjectId("5e4c0cb05d93261e4bc9ea2e"), "ListOfName": ["Chris", "David"] }

Example: Exact Match Query

Find documents where ListOfName is exactly the string "Chris" (not an array containing "Chris") ?

db.demo290.find({
    $and: [
        {"ListOfName.0": {$exists: false}},
        {"ListOfName": "Chris"}
    ]
});
{ "_id": ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName": "Chris" }

How It Works

  • {"ListOfName.0": {$exists: false}} ensures the field is NOT an array (arrays have index 0)
  • {"ListOfName": "Chris"} matches the exact string value
  • $and combines both conditions for precise filtering

Conclusion

Use $exists: false with array index notation to distinguish between string values and arrays. This approach ensures exact field type and value matching in MongoDB queries.

Updated on: 2026-03-15T02:18:54+05:30

887 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements