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 element in array of MongoDB?
To match elements in arrays in MongoDB, you can use the $or operator to search for documents where any array element matches one or more conditions. This approach is useful when you want to find documents containing arrays with specific field values.
Syntax
db.collection.find({
$or: [
{"arrayField.subfield1": "value1"},
{"arrayField.subfield2": "value2"}
]
}).limit(1);
Sample Data
db.matchElementInArrayDemo.insertMany([
{
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "US", "StudentSkills": "MongoDB"},
{"StudentCountryName": "UK", "StudentSkills": "Java"}
]
},
{
"StudentName": "Chris",
"StudentOtherDetails": [
{"StudentCountryName": "AUS", "StudentSkills": "PHP"},
{"StudentCountryName": "US", "StudentSkills": "MongoDB"}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd423282cba06f46efe9ee2"),
ObjectId("5cd423412cba06f46efe9ee3")
]
}
Display All Documents
db.matchElementInArrayDemo.find().pretty();
{
"_id": ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName": "Chris",
"StudentOtherDetails": [
{
"StudentCountryName": "US",
"StudentSkills": "MongoDB"
},
{
"StudentCountryName": "UK",
"StudentSkills": "Java"
}
]
}
{
"_id": ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName": "Chris",
"StudentOtherDetails": [
{
"StudentCountryName": "AUS",
"StudentSkills": "PHP"
},
{
"StudentCountryName": "US",
"StudentSkills": "MongoDB"
}
]
}
Match Array Elements
Find documents where array elements have either StudentCountryName as "US" OR StudentSkills as "MongoDB" ?
db.matchElementInArrayDemo.find({
$or: [
{"StudentOtherDetails.StudentCountryName": "US"},
{"StudentOtherDetails.StudentSkills": "MongoDB"}
]
}).limit(1);
{
"_id": ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName": "Chris",
"StudentOtherDetails": [
{
"StudentCountryName": "US",
"StudentSkills": "MongoDB"
},
{
"StudentCountryName": "UK",
"StudentSkills": "Java"
}
]
}
Conclusion
Use $or operator with dot notation to match elements in arrays based on multiple field conditions. The query returns documents where any array element satisfies at least one of the specified criteria.
Advertisements
