I have a document in my collection testdb
that I want to match to and looks like:
{
"student": {
"first": "Joe",
"last": "Johnson"
},
"semester": [{
"semesterName": "Spring2021",
"courses": [{
"title": "Calculus 1",
"professor": "Erik Paulson",
"TA": "Paul Matthews"
},
{
"title": "Computer Science 1",
"professor": "Dennis Ritchie",
"TA": "Ken Thompson"
}
]
}]
}
I want to match on the title
attribute in the courses
array and return the professor
attribute without all of its nesting.
So I have the following query:
db.testcol.aggregate([
{ $match: { "semester.courses.title" : "Calculus 1" } },
{ $project: { "professor" : 1, "_id" : 0 } },
{ $addFields: { "professor": "$semester.courses.professor" } },
]);
but I seem to be getting an output of just { }
when I want an output of { "professor" : "Erik Paulson" }
.
Can somebody explain why this is happening and how I can fix it? My logic is that I am using $addFields
to set the new professor
attribute to be the professor
attribute inside of the array of course
objects whenever there is a match to the desired course title
. I am then using $project
to return only the new attribute.