MongoDB $arrayToObject Operator

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

What You’ll Learn

The $arrayToObject operator converts an array of key-value pairs into a single object. It is useful when your data stores properties as an array (like metadata or settings) and you need a normal document shape for querying or display.

01

Array → Object

Reshape key-value data.

02

k / v Format

Use k and v fields.

03

Tuple Format

Use [key, value] pairs.

04

Field Arrays

Transform document fields.

05

Use Cases

Settings, specs, metadata.

06

Inverse

Pair with $objectToArray.

Definition and Usage

In MongoDB’s aggregation framework, the $arrayToObject operator takes an array where each element represents one key-value pair and returns a single object. For example, an array like [ { k: "color", v: "red" }, { k: "size", v: "L" } ] becomes { color: "red", size: "L" }.

💡
Beginner Tip

Think of $arrayToObject as the opposite of $objectToArray. One turns objects into arrays; the other turns arrays back into objects.

📝 Syntax

The $arrayToObject operator takes one array expression:

mongosh
{ $arrayToObject: <array expression> }

Supported Array Element Formats

mongosh
// Format 1: k / v documents
[
  { k: "color", v: "red" },
  { k: "size",  v: "L" }
]

// Format 2: two-element arrays
[
  [ "color", "red" ],
  [ "size",  "L" ]
]

Syntax Rules

  • Each key (k or first tuple element) must be a string.
  • Values (v or second tuple element) can be any BSON type.
  • Use inside stages like $project, $addFields, or $set.
  • Duplicate keys: the last value wins.
  • An empty input array returns an empty object {}.

💡 Input → Output Example

Input: [ { k: "a", v: 1 }, { k: "b", v: 2 } ]
Output: { a: 1, b: 2 }
Input: [ ["x", true], ["y", false] ]
Output: { x: true, y: false }

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (array transform)
Syntax{ $arrayToObject: <array> }
Key format{ k, v } or [ key, value ]
Key typeString (required)
Inverse operator$objectToArray
k / v
{
  k: "a",
  v: 1
}

Document format

Tuple
[
  "a",
  1
]

Array format

Field
{
  $arrayToObject: "$specs"
}

From document field

Empty
{
  $arrayToObject: []
}

Returns {}

Examples Gallery

Convert product specs, user settings, and literal key-value arrays into easy-to-read objects.

📚 Key-Value Arrays

Transform stored metadata arrays into objects with $project.

Sample Input Documents

Suppose you have a products collection with a specs array in k / v format:

mongosh
[
  {
    "_id": 1,
    "name": "T-Shirt",
    "specs": [
      { "k": "color", "v": "blue" },
      { "k": "size",  "v": "M" },
      { "k": "material", "v": "cotton" }
    ]
  },
  {
    "_id": 2,
    "name": "Jacket",
    "specs": [
      { "k": "color", "v": "black" },
      { "k": "size",  "v": "L" }
    ]
  }
]

Example 1 — Basic $arrayToObject with k / v Format

Convert the specs array into a flat object:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      specsObject: { $arrayToObject: "$specs" }
    }
  }
])

How It Works

Each { k, v } pair becomes one property. The key string becomes the field name and the value becomes the field value.

📈 Practical Patterns

Use tuple arrays, transform settings, and work with literal arrays.

Example 2 — Two-Element Array Format

When pairs are stored as [ key, value ] tuples instead of k / v documents:

mongosh
db.config.aggregate([
  {
    $project: {
      label: 1,
      configObject: {
        $arrayToObject: [
          [ "debug", true ],
          [ "retries", 3 ],
          [ "region", "ap-south-1" ]
        ]
      }
    }
  }
])

How It Works

MongoDB accepts both formats in the same array. The first element is the key string; the second is the value.

Example 3 — Flatten User Settings for Reporting

Convert a preferences array into dot-accessible fields:

mongosh
db.users.aggregate([
  {
    $addFields: {
      preferencesObject: { $arrayToObject: "$preferences" }
    }
  },
  {
    $project: {
      username: 1,
      theme: "$preferencesObject.theme",
      notifications: "$preferencesObject.notifications",
      language: "$preferencesObject.language"
    }
  }
])

How It Works

$addFields creates the object first; a follow-up $project pulls individual settings into top-level columns for dashboards or exports.

Example 4 — Duplicate Keys (Last Value Wins)

If the same key appears twice, the later entry overwrites the earlier one:

mongosh
db.samples.aggregate([
  {
    $project: {
      result: {
        $arrayToObject: [
          { k: "status", v: "draft" },
          { k: "status", v: "published" }
        ]
      }
    }
  }
])
// result: { status: "published" }

How It Works

Be careful when building arrays dynamically. Duplicate keys silently keep only the last value.

🚀 Use Cases

  • Product specifications — convert attribute arrays into flat objects for display or export.
  • User preferences — flatten settings arrays into readable fields.
  • Configuration data — reshape key-value config arrays into document form.
  • ETL pipelines — normalize array-based metadata before loading into reports or APIs.

🧠 How $arrayToObject Works

1

MongoDB reads the array

The pipeline evaluates the array — a field like "$specs" or a literal array of pairs.

Input
2

Each pair becomes a property

MongoDB extracts the key string and value from each element ({ k, v } or [ key, value ]).

Transform
3

A single object is built

All pairs are merged into one object. Duplicate keys keep the last value.

Merge
=

Document-shaped output

Access fields with dot notation like $specsObject.color.

Conclusion

The $arrayToObject operator is a practical reshaping tool when your data stores properties as key-value arrays. It supports both { k, v } documents and [ key, value ] tuples, and pairs naturally with $objectToArray for round-trip conversions.

For beginners, remember: keys must be strings, duplicate keys keep the last value, and an empty array becomes {}.

💡 Best Practices

✅ Do

  • Ensure every key is a string before converting
  • Pick one format (k/v or tuples) and stay consistent
  • Watch for duplicate keys in dynamic arrays
  • Use with $objectToArray when you need the reverse
  • Follow with $project to expose individual fields

❌ Don’t

  • Mix invalid element shapes in the same array
  • Assume numeric keys work without converting to strings
  • Ignore duplicate-key overwrite behavior
  • Use when the data is already a proper object
  • Forget to validate empty arrays if you expect fields

Key Takeaways

Knowledge Unlocked

Five things to remember about $arrayToObject

Use these points when reshaping array data in aggregation pipelines.

5
Core concepts
📝 02

Two Formats

{ k, v } or [k, v].

Syntax
🛠 03

String Keys

Keys must be strings.

Rule
🔁 04

Inverse

Use $objectToArray back.

Pairing
05

Duplicates

Last value wins.

Edge case

❓ Frequently Asked Questions

$arrayToObject converts an array of key-value pairs into a single object (document shape). Each array item becomes one property in the output object.
The syntax is { $arrayToObject: <array expression> }. The array can contain documents with k and v fields, or two-element arrays of [key, value].
Two formats: { k: "keyName", v: value } objects, or [ "keyName", value ] two-element arrays. The key must be a string.
If the array contains duplicate keys, the last value wins and overwrites earlier ones in the resulting object.
$objectToArray converts an object back into an array of { k, v } pairs. The two operators are inverses.

Continue the Operator Series

Move on to $asin or review $arrayElemAt for array indexing.

Next: $asin →

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