MongoDB $getField Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Field Access

What You’ll Learn

The $getField operator reads a field value from an object when the field name may be dynamic. Use it in aggregation pipelines when dot notation cannot help — for example, when the key to read is stored in another field.

01

Dynamic Access

Read fields by name.

02

Syntax

field + input.

03

Nested Objects

Pull values from subdocs.

04

$project Stage

Shape output fields.

05

Use Cases

Metrics, configs, maps.

06

vs Dot Notation

Fixed vs dynamic paths.

Definition and Usage

In MongoDB’s aggregation framework, the $getField operator returns the value of a specified field from an object. You provide a field name (which can be a literal string or an expression) and an input object to read from. This is especially powerful when documents store flexible key-value data — like metrics maps, user preferences, or configuration objects — and you need to read whichever key the document points to.

💡
Beginner Tip

For a fixed path like "$product.name", dot notation is simpler. Reach for $getField when the field name comes from data — like field: "$metricKey" and input: "$metrics".

📝 Syntax

The $getField operator takes an object with field and input:

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

Common Patterns

mongosh
// Static field name from nested object
{ field: "name", input: "$product" }

// Dynamic field name from document field
{ field: "$metricKey", input: "$metrics" }

// Read from the full document
{ field: "$lookupKey", input: "$$ROOT" }

Syntax Rules

  • field — the name of the field to read (string literal like "name" or expression like "$metricKey").
  • input — the object to read from (field path like "$metrics" or "$$ROOT").
  • Returns null if the field does not exist or input is null.
  • Use inside stages like $project, $addFields, or $set.
  • Available in MongoDB 5.0 and later.
⚠️
$getField vs dot notation

Dot notation ("$metrics.revenue") only works when you know the field name at pipeline design time. $getField lets the field name come from document data. It also handles awkward field names that contain dots or $ prefixes.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation field-access expression operator
Syntax{ $getField: { field, input } }
InputField name + source object
OutputField value (or null)
Common stages$project, $addFields, $set
Static
{
  $getField: {
    field: "name",
    input: "$product"
  }
}

Fixed field name

Dynamic
{
  $getField: {
    field: "$metricKey",
    input: "$metrics"
  }
}

Name from field

$$ROOT
{
  $getField: {
    field: "$key",
    input: "$$ROOT"
  }
}

From full document

Missing
// field not in input
→ null

Returns null

Examples Gallery

Walk through sample data, an aggregation pipeline, and the output step by step.

📚 Product Details

Start with a inventory collection and read a nested field with a static name.

Sample Input Documents

Suppose you have an inventory collection where each document has a nested product object:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "sku": "A100",
    "product": { "name": "Laptop", "brand": "TechCo", "price": 999 }
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "sku": "B200",
    "product": { "name": "Mouse", "brand": "TechCo", "price": 29 }
  }
]

Example 1 — Read a Nested Field by Static Name

Extract product.name using $getField with a literal field name:

mongosh
db.inventory.aggregate([
  {
    $project: {
      sku: 1,
      productName: {
        $getField: {
          field: "name",
          input: "$product"
        }
      }
    }
  }
])

How It Works

  • input: "$product" points to the nested object.
  • field: "name" tells MongoDB which key to read.
  • The result is the value of product.name — same as dot notation here, but the pattern scales to dynamic names.

📈 Practical Patterns

Read metrics by dynamic key, pull from the full document, and handle flexible schemas.

Example 2 — Dynamic Field Name from Document Data

Each document stores which metric to read in metricKey:

mongosh
db.reports.aggregate([
  {
    $project: {
      reportId: 1,
      metricKey: 1,
      selectedValue: {
        $getField: {
          field: "$metricKey",
          input: "$metrics"
        }
      }
    }
  }
])

// metricKey: "revenue", metrics: { revenue: 5000, clicks: 120 }
// → selectedValue: 5000

How It Works

field: "$metricKey" resolves per document. One pipeline can read different keys without rewriting the path — dot notation cannot do this.

Example 3 — Read from the Full Document with $$ROOT

When the key to read is a top-level field name stored in lookupKey:

mongosh
db.settings.aggregate([
  {
    $project: {
      lookupKey: 1,
      resolved: {
        $getField: {
          field: "$lookupKey",
          input: "$$ROOT"
        }
      }
    }
  }
])

// lookupKey: "theme", document has theme: "dark"
// → resolved: "dark"

How It Works

$$ROOT refers to the current document. Combined with a dynamic field, you can resolve any top-level field whose name is stored in the document itself.

Example 4 — Fields with Dots in the Name

$getField can read keys that dot notation cannot express cleanly:

mongosh
db.logs.aggregate([
  {
    $project: {
      event: 1,
      dotKeyValue: {
        $getField: {
          field: "user.name",
          input: "$attributes"
        }
      }
    }
  }
])

// attributes: { "user.name": "Ana", "status": "ok" }
// → dotKeyValue: "Ana"

How It Works

The field name "user.name" is a single key in the object, not a nested path. Dot notation would look for attributes.user.name as nested objects. $getField treats the entire string as the key name.

🚀 Use Cases

  • Dynamic metrics — read whichever KPI a dashboard document points to via a key field.
  • Flexible schemas — work with documents that store arbitrary key-value attributes.
  • Configuration lookups — resolve settings when the field name is stored in the document.
  • Special field names — access keys containing dots or $ that dot notation cannot handle.

🧠 How $getField Works

1

MongoDB resolves field and input

The field expression becomes the key name; input becomes the source object.

Input
2

$getField looks up the key

MongoDB reads input[field] — like JavaScript bracket notation, not dot chaining.

Lookup
3

The value is returned

If the key exists, its value is returned. If not, the result is null.

Output
=

Dynamic field value

You get the right value even when the field name varies per document.

Conclusion

The $getField operator is essential when field names are dynamic or contain special characters. It gives aggregation pipelines the same flexibility as JavaScript bracket notation — read any key from any object at runtime.

For beginners, remember two parts: field (the key to read) and input (the object to read from). Use dot notation for fixed paths; use $getField when the path depends on document data.

💡 Best Practices

✅ Do

  • Use dot notation when the field path is fixed and known
  • Use $getField when the field name comes from document data
  • Pass $$ROOT as input for top-level dynamic lookups
  • Handle missing keys — $getField returns null
  • Pair with $setField when you also need to write dynamic keys

❌ Don’t

  • Replace simple dot paths with $getField unnecessarily
  • Forget that field is the key name, not a full path
  • Assume nested paths — field: "a.b" is one key, not nested
  • Use $getField as a query filter outside expressions
  • Expect it on MongoDB versions before 5.0

Key Takeaways

Knowledge Unlocked

Five things to remember about $getField

Use these points when accessing fields dynamically in pipelines.

5
Core concepts
📝 02

Two Parts

field + input.

Syntax
🛠 03

Bracket Style

Like obj[key].

Usage
🔍 04

Flexible Data

Metrics, configs.

Use case
05

Not Dot Paths

Key name, not nested.

Edge case

❓ Frequently Asked Questions

$getField returns the value of a named field from an object. Unlike dot notation, the field name can be dynamic — stored in another field or computed at runtime. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $getField: { field: <string expression>, input: <object expression> } }. The field argument is the name to look up; input is the object to read from.
Use $getField when the field name is not known at write time — for example, when a document stores which metric to read in a field like metricKey. Dot notation only works with fixed field paths.
Yes. $getField is useful for field names that contain dots or start with a dollar sign, where dot notation would fail or require awkward escaping.
Use $getField inside expression stages such as $project, $addFields, and $set when you need dynamic or safe field access on embedded objects.

Explore More MongoDB Operators

Continue with $gt for greater-than comparisons, or review $function for custom JavaScript.

Next: $gt →

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.

5 people found this page helpful