MongoDB $setField Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $setField?

$setField is a MongoDB aggregation expression that returns a copy of an object with one field set to a value. The field name can be fixed or dynamic (from another field). Pair it with $getField to read that value back.

Remember
$setField = object + field = value  (returns new object)

{ $setField: {
    field: <name string>,
    input: <object>,
    value: <expression>
  }
}

existing field → replaced
missing field  → added
value $$REMOVE → field dropped

$input is copied — original expression not mutated
UsePrefer
Set field by (dynamic) name$setField
Read field by (dynamic) name$getField
Fixed top-level field$addFields / $set

How to Use $setField in MongoDB

Name the field, pass the object, and supply the new value.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to the object (for example "$profile").
  3. Set field to a string name (literal or "$key").
  4. Set value to the new contents (or "$$REMOVE" to drop the field).
PieceRequired?Role
fieldYesName to write (string expression)
inputYesObject to copy and update
valueYesNew value (or $$REMOVE)

Pseudocode

Pseudocode
obj  = evaluate(input)
name = evaluate(field)     // must be a string
val  = evaluate(value)

result = shallow_copy(obj)
if val is $$REMOVE:
    delete result[name]
else:
    result[name] = val

emit { ..., field: result }

Cheat Sheet

Keep these facts handy while updating objects by field name.

TopicDetail
TypeAggregation expression (returns an object)
Syntax{ $setField: { field, input, value } }
Missing fieldAdded
Existing fieldReplaced
Removevalue: "$$REMOVE"
Dynamic namefield: "$key"
Sampleprofile + age: 14

Live Preview

Start from { city: "Chennai" } and apply $setField-style updates.

Simulates { $setField: { field, input, value } }.

Result
input = { city: "Chennai" }
field = "age"
value = 14

→ { city: "Chennai", age: 14 }

Worked Walkthrough — Add Age to Profile

Asha’s profile only has city. We add age: 14 with $setField and keep the city.

Calculation
input = { city: "Chennai" }
field = "age"
value = 14

copy object
set age → 14

result = { city: "Chennai", age: 14 }

(original profile expression is not changed;
 we assign the result back with $addFields)

MongoDB Examples

We use one student with a nested profile. First insert the sample, then add age, then set a field whose name comes from another field. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine student Asha with profile: { city: "Chennai" } and a key name "score" for later. We save it in students.

mongosh
db.students.insertOne({
  _id: 1,
  name: "Asha",
  key: "score",
  profile: { city: "Chennai" }
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in students. Run find() to see it:

mongosh
db.students.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id
name"Asha"Student name
key"score"Dynamic field name for Example 3
profile{ city: "Chennai" }Object we will update
Picture
profile: { city: "Chennai" }
              +
         age: 14
              ↓
profile: { city: "Chennai", age: 14 }

How It Works

  1. Insert once. insertOne adds Asha’s document to students.
  2. Keep a nested object. profile is the input for $setField.
  3. find() shows the same shape. Ready for Example 2.

Example 2 — Add a Field

Goal: replace profile with a copy that also has age: 14.

mongosh
db.students.aggregate([
  {
    $addFields: {
      profile: {
        $setField: {
          field: "age",
          input: "$profile",
          value: 14
        }
      }
    }
  }
]);

How It Works

  1. Copy profile. input: "$profile" starts as { city: "Chennai" }.
  2. Write age. field: "age" and value: 14 add the new key.
  3. Assign back. $addFields stores the returned object in profile.

Example 3 — Dynamic Field Name

Same student, but the field name comes from key (("score"). We write 95 under that name.

mongosh
db.students.aggregate([
  {
    $addFields: {
      profile: {
        $setField: {
          field: "$key",
          input: "$profile",
          value: 95
        }
      }
    }
  }
]);

How It Works

  1. Read the name. field: "$key" resolves to "score".
  2. Write the value. value: 95 becomes profile.score.
  3. Why this matters. Dot notation cannot use a runtime field name; $setField can.

Edge Cases & Pitfalls

Check these before updating objects with dynamic names.

assign

You must store the result

$setField only returns a new object. Wrap it in $addFields / $set (or an update pipeline) to keep it.

remove

$$REMOVE drops the field

Use value: "$$REMOVE" when you want the named field gone from the returned object.

name

field must be a string

The resolved field expression has to be a string. Numbers or objects as names will error.

nested

One level at a time

$setField sets a single key on one object. For deep paths, nest calls or rebuild the parent object.

Performance Notes

ApproachCostBest for
$setField on small objectsCheap object copyDynamic / awkward names
Fixed-name $addFieldsSimplerKnown top-level fields
Huge nested objectsCopy cost growsKeep payloads lean

Prefer plain $addFields when the field name is fixed. Reach for $setField when the name is dynamic or hard to express with dots.

Key Takeaways

  • Role: return an object with one field set.
  • Parts: field + input + value.
  • Dynamic: field: "$key" works at runtime.
  • Sample: profile + age: 14 → city kept, age added.

One line: $setField answers “give me this object with field X set to Y.”

Frequently Asked Questions

$setField returns a copy of an object with one field set to a given value. If the field exists, it is replaced; if not, it is added. The field name can be a fixed string or a dynamic expression.
Use { $setField: { field: <name>, input: <object>, value: <expression> } }. field is the name to write, input is the object to copy, and value is the new contents.
$getField reads a field from an object. $setField writes a field and returns the updated object. They pair well for dynamic field access.
Use $addFields / $set when the top-level field name is fixed. Prefer $setField when the name is dynamic, contains dots, or starts with $, or when you are updating a nested object expression.
Yes. Set value to "$$REMOVE" to drop that field from the returned object.
No. It returns a new object expression result. Persist it with $addFields / $set (or an update pipeline) if you want it written back.

Next: $setIntersection

Find elements that appear in every input array.

$setIntersection tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful