0
0
MongoDBquery~5 mins

$addFields for computed fields in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $addFields stage do in a MongoDB aggregation pipeline?
It adds new fields or modifies existing fields in the documents by computing values, without removing any existing fields.
Click to reveal answer
beginner
How can you use $addFields to create a new field that is the sum of two existing fields, price and tax?
Use $addFields with an expression like: { totalCost: { $add: ["$price", "$tax"] } } to add a new field totalCost.
Click to reveal answer
beginner
Can $addFields remove fields from documents?
No, $addFields only adds or updates fields. To remove fields, use $project or $unset.
Click to reveal answer
intermediate
What happens if you use $addFields to add a field that already exists in the document?
The existing field is overwritten with the new computed value.
Click to reveal answer
intermediate
Give an example of using $addFields to add a field isAdult that is true if age is 18 or more, false otherwise.
Use: { $addFields: { isAdult: { $gte: ["$age", 18] } } }. This adds isAdult as true or false based on age.
Click to reveal answer
What is the main purpose of the $addFields stage in MongoDB?
ASort documents
BAdd or update fields in documents
CRemove fields from documents
DGroup documents
Which operator can you use inside $addFields to sum two fields price and tax?
A$multiply
B$sum
C$add
D$concat
If you want to remove a field from documents, which stage should you use instead of $addFields?
A$unset
B$addFields
C$group
D$match
What happens if $addFields adds a field that already exists?
AThe existing field is overwritten
BThe field is ignored
CThe field is duplicated
DIt causes an error
How would you add a boolean field isAdult that is true if age is 18 or more?
A{ isAdult: { $lt: ["$age", 18] } }
B{ isAdult: { $ne: ["$age", 18] } }
C{ isAdult: { $eq: ["$age", 18] } }
D{ isAdult: { $gte: ["$age", 18] } }
Explain how $addFields can be used to compute new fields in MongoDB documents.
Think about how you can add new information to each document without losing old data.
You got /4 concepts.
    Describe a scenario where $addFields is useful in a data aggregation pipeline.
    Consider when you want to enrich your data with new calculated details.
    You got /4 concepts.