Write an equality in MongoDB without using $eq operator

In MongoDB, you can write equality queries without using the $eq operator by using the implicit equality syntax. This involves directly specifying the field name and value in the query document.

Syntax

db.collection.find({"fieldName": "value"});

Sample Data

Let us first create a collection with documents ?

db.operatorDemo.insertMany([
    {"StudentSubject": ["MongoDB", "MySQL", "Java"]},
    {"StudentSubject": ["Java", "C", "C++"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cef94eaef71edecf6a1f6a2"),
        ObjectId("5cef94faef71edecf6a1f6a3")
    ]
}

Display all documents from the collection ?

db.operatorDemo.find();
{
    "_id": ObjectId("5cef94eaef71edecf6a1f6a2"),
    "StudentSubject": [
        "MongoDB",
        "MySQL",
        "Java"
    ]
}
{
    "_id": ObjectId("5cef94faef71edecf6a1f6a3"),
    "StudentSubject": [
        "Java",
        "C",
        "C++"
    ]
}

Example: Equality Query Without $eq

Find documents where the StudentSubject array contains "MongoDB" ?

db.operatorDemo.find({"StudentSubject": "MongoDB"});
{
    "_id": ObjectId("5cef94eaef71edecf6a1f6a2"),
    "StudentSubject": [
        "MongoDB",
        "MySQL",
        "Java"
    ]
}

Key Points

  • The implicit equality syntax {"field": "value"} is equivalent to {"field": {$eq: "value"}}
  • This works for array fields by checking if the value exists in the array
  • The implicit syntax is more concise and commonly used for simple equality checks

Conclusion

MongoDB's implicit equality syntax provides a clean way to write equality queries without explicitly using the $eq operator. Simply specify the field and value directly in the query document for effective equality matching.

Updated on: 2026-03-15T01:26:08+05:30

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements