MongoDB $objectToArray Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Object Transform

What You’ll Learn

The $objectToArray operator converts an object into an array of { k, v } pairs. Use it when you need to iterate over dynamic keys, flatten metadata, or reshape nested objects for reporting.

01

Object → Array

Split into k/v pairs.

02

k / v Output

Standard pair format.

03

$unwind Ready

One row per key.

04

Field Objects

Transform document fields.

05

Use Cases

Settings, attributes.

06

Inverse

Pair with $arrayToObject.

Definition and Usage

In MongoDB’s aggregation framework, the $objectToArray operator takes an object and returns an array where each property becomes one element. For example, { theme: "dark", lang: "en" } becomes [ { k: "theme", v: "dark" }, { k: "lang", v: "en" } ].

This is especially useful for objects with dynamic or unknown keys — user preferences, product attributes, or configuration maps — where you cannot hard-code field names.

💡
Beginner Tip

Think of $objectToArray as the opposite of $arrayToObject. Convert to an array when you need to loop, filter, or sort individual key-value pairs with $unwind.

📝 Syntax

The $objectToArray operator takes one object expression:

mongosh
{ $objectToArray: <object expression> }

Output Format

mongosh
// Input object:
{ color: "blue", size: "M" }

// Output array:
[
  { k: "color", v: "blue" },
  { k: "size",  v: "M" }
]

Syntax Rules

  • Argument — any expression that evaluates to an object (field path or literal).
  • Output — array of documents with string k and any-type v.
  • Use inside $project, $addFields, or $set.
  • An empty object {} returns an empty array [].
  • null or missing input returns null.
  • Pair with $unwind to process one key-value pair per document.

💡 Object ↔ Array Round Trip

$objectToArray{ a: 1, b: 2 }[ { k: "a", v: 1 }, { k: "b", v: 2 } ]
$arrayToObject — reverses the conversion back to an object
$unwind — after $objectToArray, access $pair.k and $pair.v

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (object transform)
Syntax{ $objectToArray: <object> }
Output format[ { k: string, v: any }, ... ]
Empty objectReturns []
Inverse operator$arrayToObject
From field
{
  $objectToArray: "$settings"
}

Document field

Literal
{
  $objectToArray: {
    a: 1,
    b: 2
  }
}

Inline object

+ $unwind
{
  $unwind: "$pairs"
}

One row per pair

Empty {}
{
  $objectToArray: {}
}

Returns []

Examples Gallery

Convert settings objects to arrays, unwind key-value pairs, filter by key, and round-trip with $arrayToObject.

📚 User Settings

Transform a settings object into a key-value array with $project.

Sample Input Documents

Suppose you have a users collection with a settings object:

mongosh
[
  {
    "_id": 1,
    "username": "alice",
    "settings": {
      "theme": "dark",
      "notifications": true,
      "language": "en"
    }
  },
  {
    "_id": 2,
    "username": "bob",
    "settings": {
      "theme": "light",
      "notifications": false,
      "language": "fr"
    }
  }
]

Example 1 — Basic $objectToArray

Convert the settings object into an array of pairs:

mongosh
db.users.aggregate([
  {
    $project: {
      username: 1,
      settingsArray: { $objectToArray: "$settings" }
    }
  }
])

How It Works

Each property in settings becomes one array element. The property name goes into k and the value goes into v.

📈 Practical Patterns

Unwind pairs, filter by key, and round-trip with $arrayToObject.

Example 2 — $unwind for One Row Per Setting

Flatten settings so each key-value pair is its own document:

mongosh
db.users.aggregate([
  {
    $project: {
      username: 1,
      pair: { $objectToArray: "$settings" }
    }
  },
  { $unwind: "$pair" },
  {
    $project: {
      username: 1,
      settingKey: "$pair.k",
      settingValue: "$pair.v"
    }
  }
])

How It Works

$objectToArray creates the array; $unwind splits it into separate documents. This pattern is ideal for pivot tables and key-value reporting.

Example 3 — Filter by a Specific Key

Find users whose theme setting is "dark":

mongosh
db.users.aggregate([
  {
    $project: {
      username: 1,
      pairs: { $objectToArray: "$settings" }
    }
  },
  { $unwind: "$pairs" },
  {
    $match: {
      "pairs.k": "theme",
      "pairs.v": "dark"
    }
  },
  {
    $project: {
      username: 1,
      theme: "$pairs.v"
    }
  }
])

How It Works

After converting and unwinding, $match filters on pairs.k and pairs.v. This works for any dynamic key without knowing field names in advance at schema design time.

Example 4 — Round Trip with $arrayToObject

Convert to array, modify, and convert back to an object:

mongosh
db.users.aggregate([
  {
    $project: {
      username: 1,
      settingsRestored: {
        $arrayToObject: {
          $objectToArray: "$settings"
        }
      }
    }
  }
])

How It Works

$objectToArray followed by $arrayToObject reconstructs the original object. Insert a $map or $filter stage between them to transform individual pairs.

Bonus — Product Attributes to Rows

Turn dynamic product attributes into exportable rows:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      attr: { $objectToArray: "$attributes" }
    }
  },
  { $unwind: "$attr" },
  {
    $project: {
      product: "$name",
      attribute: "$attr.k",
      value: "$attr.v"
    }
  }
])

// attributes: { weight: 2.5, color: "blue" }
// → two rows: weight/2.5 and color/blue

How It Works

Products with different attribute keys (weight, color, size, etc.) can all be normalized into a consistent three-column format for CSV export or BI tools.

🚀 Use Cases

  • Dynamic key iteration — process objects when field names are not fixed at design time.
  • Settings flattening — convert preference objects into rows for reporting.
  • Attribute normalization — reshape product specs or metadata for export.
  • Pipeline transforms — modify key-value pairs with $map before converting back with $arrayToObject.

🧠 How $objectToArray Works

1

MongoDB reads the object

The pipeline evaluates the object expression — a field like "$settings" or a literal.

Input
2

Each property becomes a pair

MongoDB extracts every key as k (string) and every value as v (any type).

Transform
3

An array is returned

All pairs are collected into one array, ready for $unwind, $filter, or $map.

Output
=

Iterable key-value data

Access .k and .v after $unwind for flexible reporting.

Conclusion

The $objectToArray operator converts objects into arrays of { k, v } pairs in MongoDB aggregation pipelines. It is essential when you need to iterate, filter, or reshape data with dynamic keys.

Pair it with $unwind for row-per-key output and $arrayToObject for round-trip conversions. Next in the series: $or.

💡 Best Practices

✅ Do

  • Use $objectToArray for dynamic or unknown object keys
  • Follow with $unwind when you need one document per pair
  • Filter on .k and .v after unwinding
  • Pair with $arrayToObject for round-trip transforms
  • Handle empty objects ({}[]) in downstream stages

❌ Don’t

  • Use when you already know all field names (direct projection is simpler)
  • Forget that null input returns null, not []
  • Assume key order in the output array matches insertion order in all cases
  • Nest $objectToArray without planning for array size growth
  • Confuse output { k, v } format with [ key, value ] tuples ($arrayToObject accepts both)

Key Takeaways

Knowledge Unlocked

Five things to remember about $objectToArray

Use these points when converting objects in aggregation pipelines.

5
Core concepts
📝 02

One Argument

Object expression.

Syntax
🛠 03

k / v Output

Standard pair shape.

Format
🔁 04

+ $unwind

One row per key.

Pattern
🔄 05

Inverse

$arrayToObject back.

Pairing

❓ Frequently Asked Questions

$objectToArray converts an object into an array of key-value pairs. Each property becomes { k: "keyName", v: value }. It is the inverse of $arrayToObject.
The syntax is { $objectToArray: <object expression> }. Pass a field path like "$settings" or a literal object expression.
An array of documents with k (string key) and v (value) fields. For example, { theme: "dark", lang: "en" } becomes [{ k: "theme", v: "dark" }, { k: "lang", v: "en" }].
Yes. Convert the object to an array, then $unwind the array to get one document per key-value pair. Access the key with $pairs.k and the value with $pairs.v.
$arrayToObject converts an array of { k, v } pairs (or [key, value] tuples) back into a single object. The two operators are inverses.

Continue the Operator Series

Move on to $or for logical OR conditions, or review $arrayToObject for the inverse transform.

Next: $or →

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