In MongoDB, $elemMatch and dot notation are used to find the match in the array of objects. But both have some difference.
Let me explain this with an example. Let say we have a document like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
db.classes.insert([{
"_id" : 1,
"name" : "Class 10",
"students" : [
{ "rollNo" : 1, "name" : "Saurabh", "score" : 65, "section" : "A" },
{ "rollNo" : 2, "name" : "Gaurav", "score" : 90, "section" : "B" },
{ "rollNo" : 3, "name" : "Mrigank", "score" : 75, "section" : "C" }
]
},
{
"_id" : 2,
"name" : "Class 11",
"students" : [
{ "rollNo" : 1, "name" : "Satendra", "score" : 88, "section" : "B" },
{ "rollNo" : 2, "name" : "Shakshi", "score" : 91, "section" : "A" },
{ "rollNo" : 3, "name" : "Sachin", "score" : 82, "section" : "A" },
{ "rollNo" : 4, "name" : "Urvi", "score" : 55, "section" : "C" }
]
},
{
"_id" : 3,
"name" : "Class 12",
"students" : [
{ "rollNo" : 1, "name" : "Radha", "score" : 77, "section" : "B" },
{ "rollNo" : 2, "name" : "Geeta", "score" : 81, "section" : "A" }
]
}])
|
Now let me find the class name whose students has scored greater than 86.
If using the dot notation then here is the example:
1
|
db.classes.find({'students.score':{'$gt':86}},{_id:0, 'name':1);
|
The result will be :
1
2
|
{ "name" : "Class 10" }
{ "name" : "Class 11" }
|
Now If I find the class name whose students has scored greater than 86 and their section is A by using dot notation.
1
|
db.classes.find({'students.score':{'$gt':86},'students.section':'A'},{_id:0, 'name':1);
|
The result will be:
1
2
3
|
{ "name" : "Class 10" }
{ "name" : "Class 11" }
{ "name" : "Class 12" }
|
Hence if we are using dot notation, Any condition match in students array, like score or section will be returning document.
But what if we wanted to match every condition? The answer is: We use $elemMatch for that. ...