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
How can I use $elemMatch on first level array in MongoDB?
You can use $in operator instead of $elemMatch on first level array. For simple value matching in arrays, $in provides better performance and cleaner syntax.
Syntax
db.collection.find({
"arrayField": { $in: ["value1", "value2"] }
});
Sample Data
Let us create a collection with documents containing first−level arrays ?
db.firstLevelArrayDemo.insertMany([
{
"StudentName": "Chris",
"StudentTechnicalSkills": ["MongoDB", "MySQL", "SQL Server"]
},
{
"StudentName": "Robert",
"StudentTechnicalSkills": ["C", "Java", "C++"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca2360f66324ffac2a7dc71"),
ObjectId("5ca2362766324ffac2a7dc72")
]
}
Example: Query First Level Array
Find students who have "MongoDB" as a technical skill ?
db.firstLevelArrayDemo.find({
"StudentTechnicalSkills": { $in: ["MongoDB"] }
});
{
"_id": ObjectId("5ca2360f66324ffac2a7dc71"),
"StudentName": "Chris",
"StudentTechnicalSkills": [
"MongoDB",
"MySQL",
"SQL Server"
]
}
Key Points
-
$inmatches documents where the array field contains any of the specified values. - For first−level arrays with simple values,
$inis more efficient than$elemMatch. -
$elemMatchis typically used for arrays containing objects or complex matching conditions.
Conclusion
Use $in operator for matching values in first−level arrays. It provides simpler syntax and better performance compared to $elemMatch for basic value matching scenarios.
Advertisements
