[Chapter 2 - Lab 2 Bring It All Together] Using Formulas in $addFields vs. $project

Is there a difference between $addFields and $project when using certain operators? (I searched for an answer on Google and Stack Overflow and the MongoDB Manual but couldn’t find one, so I thought I’d ask my question here.)

My situation: I was completely stumped; I kept receiving null values for scaled_votes and normalized_rating when using the formulas provided in the handout inside of $addFields. I removed $addFields and used both formulas inside $project while troubleshooting and, suddenly, I received proper values and was able to complete the lab.

To clarify, I used two addFields (one for scaled_votes and one for normalized_rating), hard-coded the values from the handout, and referenced imdb.votes and later scaled_votes using (i.e., $imdb.votes).

Hey @Nick_74740

From the $addFields Docs

The $addFields stage is equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

So they can use the same aggregation expression operators.

Where you trying to access these fields in the same stage? Like the follow example. If so you will not be able to.

    $match: {
      field: { expresssion }
    $addFields: {
      newField: { $add: ['$fieldOnDoc', '$anotherFieldOnDoc']},
      plusTwo: { $add: ['$newField', ...]} // $newField will be null here

I accessed them in different stages, with the first $addFields scaling imdb.votes and the second calculating the normalized_rating.

Thank you for the clarification on $project vs. $addFields! It may have been something else I didn’t notice that was changed along with switching to using $project. Ultimately, I’m satisfied that I was able to solve the lab.