MongoDB – $eq Operator

MongoDB $eq operator or equality operator is a comparison operator. The $eq operator matches documents where the value of the field is equal to the specified value.

Important Points:

  • If the given value is a document, then the order of the fields in the document is important.
  • If the given value is an array, then MongoDB matches the documents where the field contains an element that exactly matches the specified array.

Syntax

{field: {$eq: value}}

or

{field: value}

MongoDB $eq Operator Example

In the following examples, we are working with:

Database: w3wiki 

Collection: employee 

Document: five documents that contain the details of the employees in the form of field-value pairs.

Example 1

In this example, we are selecting those documents where the value of the salary field is equal to 30000.

Query

db.employee.find({salary: {$eq: 30000}}).pretty()

You can also use the syntax:

db.employee.find({salary: 30000}).pretty()

Output

Example 2

In this example, we are selecting those documents where the first name of the employee is equal to Amu. We are specifying conditions on the field in the embedded document using dot notation in this example.

Query

db.employee.find({"name.first": {$eq: "Amu"}}).pretty()

Or, you can also write the query as

db.employee.find({"name.first": "Amu"}).pretty()

Output:

Example 3

In this example, we are selecting those documents where the language array contains an element with value “C++”.

Query

db.employee.find({language: {$eq: "C++"}}).pretty()

Or, you can also write the query as

db.employee.find({language: "C++"}).pretty()

Output:

Example 4

In this example, we are selecting those documents where the language array is equal to the specified array.

Query

db.employee.find({language: {$in: ["C#", "Java"]}}).pretty()

Or, you can also write the query as:

db.employee.find({language: {$all: ["C#", "Java"]}}).pretty()

Output:

Key Takeaways About $eq Operator

  • The $eq Operator is one of the comparison operator in MongoDB.
  • It is used to match values exactly in MongoDB.
  • It is used to filter data based on exact match.
  • If the specified <value> is an array, MongoDB matches documents where the <field> matches the array exactly or the <field> contains an element that matches the array exactly.

Contact Us