Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Alternative of MongoDB operator $eq to get similar result
For writing an equality query in MongoDB, you can use implicit equality with find() instead of the explicit $eq operator. Both approaches produce identical results when matching field values.
Syntax
// Using implicit equality (alternative to $eq)
db.collection.find({"field": "value"});
// Equivalent using explicit $eq operator
db.collection.find({"field": {$eq: "value"}});
Sample Data
db.demo145.insertMany([
{"ListOfNames": ["Chris", "David", "Mike"]},
{"ListOfNames": ["Bob", "John"]}
]);
{
"acknowledged": true,
"insertedId": ObjectId("5e32f37bfdf09dd6d08539bb")
}
{
"acknowledged": true,
"insertedId": ObjectId("5e32f384fdf09dd6d08539bc")
}
Display all documents from the collection ?
db.demo145.find();
{"_id": ObjectId("5e32f37bfdf09dd6d08539bb"), "ListOfNames": ["Chris", "David", "Mike"]}
{"_id": ObjectId("5e32f384fdf09dd6d08539bc"), "ListOfNames": ["Bob", "John"]}
Example: Implicit Equality vs $eq Operator
Find documents where the array contains "John" using implicit equality ?
db.demo145.find({"ListOfNames": "John"});
{"_id": ObjectId("5e32f384fdf09dd6d08539bc"), "ListOfNames": ["Bob", "John"]}
The same result using explicit $eq operator ?
db.demo145.find({"ListOfNames": {$eq: "John"}});
{"_id": ObjectId("5e32f384fdf09dd6d08539bc"), "ListOfNames": ["Bob", "John"]}
Key Points
-
Implicit equality is shorter and more commonly used than explicit
$eq. - Both approaches work identically for array element matching and field value comparison.
- Use explicit
$eqonly when building complex query expressions or for code clarity.
Conclusion
Implicit equality using find({"field": "value"}) is the preferred alternative to $eq operator. It produces identical results with cleaner, more readable syntax for simple equality queries.
Advertisements
