0

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.

nutella100
  • 75
  • 5
  • The `$project` stage is removed the `semester` field before the `$addFields` can extract data from it. – Joe Feb 22 '21 at 05:09
  • how can I get around this? Do I just switch the ```$project``` and ```$addFields```? – nutella100 Feb 22 '21 at 05:21
  • You dont need the `$project` stage. Also see this post: [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – prasad_ Feb 22 '21 at 09:36

1 Answers1

1

Explanation: Mistake is in your $project stage. property professor is two level inside the document which must be referenced as semester.courses.professor. Accessing it as professor will result in empty value.

So you can fix it using below query. Try this:

db.testcol.aggregate([
    { $unwind: "$semester" },
    { $unwind: "$semester.courses" },
    { $match: { "semester.courses.title" : "Calculus 1" } },
    {
        $project: {
            "_id": 0,
            "professor": "$semester.courses.professor"
        }
    }
]);

Output:

{
    "professor" : "Erik Paulson"
}
Dheemanth Bhat
  • 3,594
  • 1
  • 9
  • 28