MongoDB $getField Operator

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

What Is $getField?

$getField is a MongoDB aggregation expression that returns the value of a named field from an object. The name can be a fixed string or another field—useful when you do not know the path at write time.

Remember
$getField = object[fieldName] for aggregation

{
  $getField: {
    field: <string expression>,
    input: <object expression>
  }
}

field  → name to look up (can be dynamic)
input  → object to read (omit → current doc)

missing field → missing / null in output
pair with $setField to write by name
UsePrefer
Read by fixed or dynamic name$getField
Write / replace by name$setField
Known fixed pathDot notation ("$metrics.sales")

How to Use $getField in MongoDB

Name the field, point at the object, and emit the looked-up value.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to the object (for example "$metrics").
  3. Set field to a literal ("sales") or a dynamic value ("$pick").
  4. Use the returned value like any other expression result.
PieceRequired?Role
fieldYesField name string (or expression)
inputNoObject to read; defaults to current document

Pseudocode

Pseudocode
for each document:
    obj  = evaluate(input) or current document
    name = evaluate(field)
    if obj is null or missing:
        result = null
    else if name is not a field on obj:
        result = missing / null
    else:
        result = obj[name]
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while reading fields by name.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $getField: { field, input } }
Dynamic namefield: "$pick"
vs dot pathDot path needs a fixed name
Special namesHelpful for . or $ in field names
Write sibling$setField
Sample checkmetrics.sales via name "sales" → 45

Live Preview

Watch $getField pull a metric from an object by field name.

Simulates $getField on { views: 120, sales: 45, rating: 4 }.

Result
input = { views: 120, sales: 45, rating: 4 }
field = "sales"
$getField → 45

Worked Walkthrough — Pick a Metric

A product stores metrics in one object. We want the sales value by field name.

Calculation
Document:
  {
    metrics: { views: 120, sales: 45 },
    pick: "sales"
  }

$getField:
  input = metrics
  field = "sales"

metrics["sales"] → 45 ✓

Dynamic version:
  field = pick  ("sales") → same 45

MongoDB Examples

We use one product with a metrics object. First read a fixed field name, then read a name stored in another field. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one product with metrics.views = 120, metrics.sales = 45, and a pick field set to "sales". We save it in a collection named products.

mongosh
db.products.insertOne({
  _id: 1,
  product: "Notebook",
  metrics: { views: 120, sales: 45, rating: 4 },
  pick: "sales"
});

How the Data Is Stored in MongoDB

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

mongosh
db.products.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
product"Notebook"Product name
metrics{ views, sales, rating }Object we will read from
pick"sales"Dynamic field name for Example 3
Picture
metrics
  views:  120
  sales:   45  ← get field "sales"
  rating:   4

pick = "sales"  ← same lookup, dynamic name

How It Works

  1. Insert once. insertOne adds a single product document to products.
  2. Metrics are nested. The values live under the metrics object.
  3. find() shows the same shape. Ready for $getField next.

Example 2 — Fixed Field Name

Goal: read sales from metrics using a literal name.

mongosh
db.products.aggregate([
  {
    $addFields: {
      chosen: {
        $getField: {
          field: "sales",
          input: "$metrics"
        }
      }
    }
  }
]);

How It Works

  1. Point at the object. input: "$metrics" selects the nested document.
  2. Look up by name. field: "sales" reads that key.
  3. Emit the value. Result is 45 in chosen.

Example 3 — Dynamic Field Name

Same product, but the field name comes from pick instead of a literal.

mongosh
db.products.aggregate([
  {
    $addFields: {
      chosen: {
        $getField: {
          field: "$pick",
          input: "$metrics"
        }
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using the Notebook metrics from Example 1.
  2. Resolve the name first. field: "$pick" becomes "sales".
  3. Same lookup result. metrics.sales → 45. Change pick to "views" and you get 120 without rewriting the path.

Edge Cases & Pitfalls

Check these before using $getField in production pipelines.

missing

Missing fields become null-ish

If the name is not on the object, you get a missing value (often shown as null). Validate pick when needed.

dot

Not a nested path walker

field: "a.b" looks for a single key literally named a.b, not nested a then b. Nest $getField or use a real nested path for deep objects.

fixed

Prefer dot notation when fixed

If the name never changes, "$metrics.sales" is clearer. Reserve $getField for dynamic or awkward names.

write

Need to write? Use $setField

$setField is the write-side twin for setting a field by name.

Performance Notes

ApproachCostBest for
Dot pathCheapest / clearestKnown fixed fields
$getFieldCheap lookupDynamic names, special keys
Many dynamic keysStill O(docs)Metric pickers, flexible schemas

Field lookup is cheap. Filter early with $match when only some documents need a dynamic read.

Key Takeaways

  • Role: read an object field by name.
  • Dynamic: field can come from another field.
  • Input: object to read; omit to use the current document.
  • Write twin: $setField.

One line: $getField answers “what is object[name]?”—even when name is dynamic.

Frequently Asked Questions

$getField returns the value of a named field from an object. The field name can be a literal string or a dynamic expression. Use it inside aggregation stages such as $project and $addFields.
Use { $getField: { field: <string expression>, input: <object expression> } }. field is the name to look up; input is the object to read from. You can omit input to use the current document.
Use $getField when the field name is stored in another field or computed at runtime. Dot notation only works with fixed paths known when you write the query.
Yes. It is especially helpful for field names that contain dots or start with $, where normal path syntax is awkward or invalid.
If the named field does not exist on the input object, $getField returns a missing value, which usually appears as null in the output.
$setField writes or replaces a field on an object by name. Together they support dynamic object shaping.

Next: $gt

Compare values with greater-than in queries and aggregation.

$gt 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