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
Match ID and fetch documents with $eq in MongoDB in case of array?
Use the $eq operator along with find() to match ID values within arrays and fetch documents. The $eq specifies an equality condition and matches documents where any array element equals the specified value.
Syntax
db.collection.find({"arrayField": {$eq: "value"}});
// Alternative (equivalent) syntax
db.collection.find({"arrayField": "value"});
Sample Data
Let us create a collection with documents ?
db.demo426.insertMany([
{"Ids": ["110", "120", "101"]},
{"Ids": ["100", "201", "401"]},
{"Ids": ["501", "600", "700"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e75e50fbbc41e36cc3cae72"),
ObjectId("5e75e51abbc41e36cc3cae73"),
ObjectId("5e75e527bbc41e36cc3cae74")
]
}
Display all documents from the collection ?
db.demo426.find().pretty();
{
"_id": ObjectId("5e75e50fbbc41e36cc3cae72"),
"Ids": [
"110",
"120",
"101"
]
}
{
"_id": ObjectId("5e75e51abbc41e36cc3cae73"),
"Ids": [
"100",
"201",
"401"
]
}
{
"_id": ObjectId("5e75e527bbc41e36cc3cae74"),
"Ids": [
"501",
"600",
"700"
]
}
Example: Match ID with $eq
Find documents where the Ids array contains the value "501" ?
db.demo426.find({"Ids": {$eq: "501"}});
{ "_id": ObjectId("5e75e527bbc41e36cc3cae74"), "Ids": ["501", "600", "700"] }
Key Points
- When using
$eqwith arrays, MongoDB checks if any element in the array matches the specified value. - For array queries,
{"field": {$eq: "value"}}and{"field": "value"}are equivalent. - The query returns the entire document if any array element matches.
Conclusion
The $eq operator effectively matches individual elements within arrays. It returns documents where any array element equals the specified value, making it useful for searching collections with array fields.
Advertisements
