i have a document:
"_id": ObjectId("THE DOCUMENT ID"),
"GROUP NAME": "First Floor",
"years": {
"0": {
"_id": "YEAR ID",
"year_classes": {
"0": {
"class_name": "CLASS A",
"_id": "CLASS ID",
"participants": {
"0": "PARTICIPANT ID"
}
},
"1": {
"class_name": "CLASS B",
"_id": "CLASS ID",
"participants": {
"0": "PARTICIPANT ID"
}
},
},
"year_name": "YEAR 1"
},
"1": {
"_id": "YEAR ID",
"year_classes": {
"0": {
"_id": "CLASS ID",
"class_name": "CLASS C",
"participants": [
]
}
},
"year_name": "YEAR 2"
},
}
It is needed to add another class to a year. The code has the year id through the $YEAR_ID variable (is a string) which the class will be added to.
So, it has to check if the class name, given by $NEW_CLASS_NAME (string variable) has already been used in that year.
I saw the $and operator for mongo but i couldn’t manage to get it to work. If it were to be an SQL it would look likt: WHERE year_id=’$YEAR_ID’ AND class_name=’$NEW_CLASS_NAME’
How could this be done in MongoDB?
UPDATE:
The Query of:
{
“years.year_classes.class_name”: $NEW_CLASS_NAME,
“years._id”: $YEAR_ID
}
Is searching the document (so it will always return TRUE) not the same array.
Is there a way to direct the query to find those two values in the same array, so a class with that name, which is in the array of classes which is in the year array with that certain ID?
When you’re comparing two conditions inside an embedded object you need to use $elemMatch.
See the general explanation here.
Your query structure would be something like:
db.coll.find({"years":{$elemMatch:{"year_classes.class_name":$NEW_CLASS_NAME,"_id":$YEAR_ID }}})