$elementMatch or dot. Which one is better? Subdocuments

Which one is better?
To access subdocument files I use the dot like db.sample_training.companies.find({offices.city: “Seattle”}). In the course they use elementMatch (db.grades.find({ “scores”: { “$elemMatch”: { “type”: “extra credit” } } }).pretty()), isn’t it easier to use the dot?
Is there any benefit to using elementMatch?
Are there any cons to use the dot?

Hello @Allison_Solano_Flore, Welcome to MongoDB University,

The dot . notation and $elemMatch both are equal when you are matching a single field.

But when you are matching multiple fields you have to understand the below things,

For Ex. you have the below 2 documents:

[
  {
    scores: [
      { type: "extra credit", score: 200 }
    ]
  },
  {
    scores: [
      { type: "extra credit", score: 100 }
    ]
  }
]

Match condition for both the fields (type, score) in subdocument:

1) dot . notation: This will return both the documents because both will search value separately.

db.grades.find({ 
  "scores.type": "extra credit",
  "scores.score": 100,
})

2) $elemMatch: This will return only second document, This will search both the fields in a single document, there should be matching fields in the same document and the same object/element.

db.grades.find({ 
  "scores": {
    "$elemMatch": {
      "type": "extra credit",
      "score": 100
    }
  }
})
1 Like

I am not too sure about the above. There is an implicit and between the 2 fields, so only the single document that has both condition will be output. The real issue, and why you want $elemMatch, is that if you have a document that looks like:

{
    scores :
    [
      { type: "extra credit", score: 200 } ,
      { type : "midterm" , score: 100 }
    ]
 }

The above will be matched, because both “scores.type” and “scores.score” match the requirement but not within the same element.

2 Likes