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
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.
Advertisements
