0
0
MongoDBquery~5 mins

$set operator for setting fields in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $set operator do in MongoDB?
The $set operator updates the value of a field in a document. If the field does not exist, it adds the field with the specified value.
Click to reveal answer
beginner
How do you use $set to change the value of a field named status to active?
You use { $set: { status: 'active' } } inside an update command to set the status field to active.
Click to reveal answer
beginner
Can $set add new fields to a document if they don't exist?
Yes, $set adds the field with the given value if the field is not already in the document.
Click to reveal answer
beginner
What happens if you use $set on a field that already has a value?
The existing value of the field is replaced with the new value provided in the $set operation.
Click to reveal answer
intermediate
Write a MongoDB update command using $set to change the age field to 30 for documents where name is 'Alice'.
db.collection.updateMany({ name: 'Alice' }, { $set: { age: 30 } })
Click to reveal answer
What does the $set operator do in MongoDB?
AIncrements a numeric field by 1
BDeletes a field from a document
CUpdates or adds a field with a specified value
DReplaces the entire document
If you want to add a new field city with value Paris to a document, which operator do you use?
A$set
B$unset
C$push
D$inc
What happens if $set is used on a field that already exists?
AThe operation fails
BThe field is removed
CThe field value is incremented
DThe field value is replaced
Which of these is a correct use of $set to update a field score to 100?
A{ $push: { score: 100 } }
B{ $set: { score: 100 } }
C{ $unset: { score: 100 } }
D{ $inc: { score: 100 } }
Which MongoDB command updates all documents with status 'pending' to have status 'complete'?
Adb.collection.updateMany({ status: 'pending' }, { $set: { status: 'complete' } })
Bdb.collection.updateMany({ status: 'pending' }, { $unset: { status: 'complete' } })
Cdb.collection.updateMany({ status: 'complete' }, { $set: { status: 'pending' } })
Ddb.collection.updateMany({ status: 'pending' }, { $inc: { status: 1 } })
Explain how the $set operator works in MongoDB updates.
Think about changing or adding information in a document.
You got /4 concepts.
    Describe a real-life example where you would use $set in a MongoDB database.
    Imagine changing details in a contact list or order system.
    You got /4 concepts.