MongoDB $arrayToObject Operator

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

What Is $arrayToObject?

$arrayToObject is a MongoDB aggregation expression that turns an array of key-value pairs into one object. Each pair becomes a field. Keys must be strings.

Remember
$arrayToObject = Object.fromEntries for aggregation

{ $arrayToObject: <array expression> }

Format A: [ { k: "color", v: "blue" }, ... ]
Format B: [ [ "color", "blue" ], ... ]

duplicate keys → last value wins
null / missing  → null
UsePrefer
Pairs array → object$arrayToObject
Object → pairs array$objectToArray
One element by index$arrayElemAt

How to Use $arrayToObject in MongoDB

Store pairs in one of the two formats, then convert them in an expression stage.

  1. Choose an expression stage ($addFields or $project).
  2. Ensure the array uses { k, v } documents or [key, value] tuples.
  3. Pass that array expression to $arrayToObject.
  4. Read the new object fields (for example attrs.color).
PieceRequired?Role
$arrayToObjectYesBuild one object from pairs
Array expressionYes{k,v} items or 2-element arrays
String keysYesNon-string keys error the pipeline

Pseudocode

Pseudocode
for each document:
    pairs = evaluate(array expression)
    if pairs is null or missing:
        result = null
    else:
        result = {}
        for each item in pairs:
            key, value = read from {k,v} or [key, value]
            result[key] = value   // later duplicates overwrite
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting pairs to objects.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $arrayToObject: <array> }
Format A{ k: <string>, v: <any> }
Format B[ <string>, <any> ]
DuplicatesLast key wins
Inverse$objectToArray
Sample check[{k:"color",v:"blue"}] → { color: "blue" }

Live Preview

Watch $arrayToObject turn product attribute pairs into one object.

Simulates { $arrayToObject: [ { k, v }, ... ] }.

Result
pairs = [
  { k: "color", v: "blue" },
  { k: "pages", v: 200 }
]
$arrayToObject → { color: "blue", pages: 200 }

Worked Walkthrough — Product Attributes

A notebook stores attributes as pairs. We want a normal object with color and pages fields.

Calculation
Input pairs:
  [
    { k: "color", v: "blue" },
    { k: "pages", v: 200 }
  ]

Build object:
  color → "blue"
  pages → 200

$arrayToObject → { color: "blue", pages: 200 }

MongoDB Examples

We use one product with both pair formats. First convert { k, v } documents, then convert [key, value] tuples. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one notebook with attributes stored two ways: as { k, v } documents and as [key, value] arrays. We save both in a collection named products.

mongosh
db.products.insertOne({
  _id: 1,
  item: "Notebook",
  pairs: [
    { k: "color", v: "blue" },
    { k: "pages", v: 200 }
  ],
  tuples: [
    ["color", "blue"],
    ["pages", 200]
  ]
});

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)
item"Notebook"Product name
pairs[{k,v}, ...]Attributes as key/value documents
tuples[[key, value], ...]Same attributes as two-element arrays
Picture
Pairs list -> one object:

  { k: "color", v: "blue" }
  { k: "pages", v: 200 }
           |
           v
  { color: "blue", pages: 200 }

Same idea with tuples:
  ["color", "blue"], ["pages", 200] -> same object

How It Works

  1. Insert once. insertOne adds a single product document to products.
  2. Two formats, same meaning. pairs and tuples both describe color and pages.
  3. find() shows the same shape. What you inserted is ready for $arrayToObject next.

Example 2 — { k, v } Format

Goal: convert pairs into an attrs object.

mongosh
db.products.aggregate([
  {
    $addFields: {
      attrs: {
        $arrayToObject: "$pairs"
      }
    }
  }
]);

How It Works

  1. Read the pairs array. MongoDB already has pairs from Example 1.
  2. Map each pair to a field. k becomes the field name; v becomes the value.
  3. Emit one object. Result is { color: "blue", pages: 200 } in attrs.

Example 3 — [key, value] Format

Same product, but convert the tuples array instead. The output object matches Example 2.

mongosh
db.products.aggregate([
  {
    $addFields: {
      attrs: {
        $arrayToObject: "$tuples"
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using the notebook from Example 1.
  2. Read each two-element array. Index 0 is the key; index 1 is the value.
  3. Same result shape. You still get { color: "blue", pages: 200 }—format B is just another input style.

Edge Cases & Pitfalls

Check these before using $arrayToObject in production pipelines.

keys

Keys must be strings

A number or boolean key fails the pipeline. Convert with $toString first if needed.

dup

Duplicate keys overwrite

The last pair for a key wins. Deduplicate earlier if you need first-wins behavior.

shape

Wrong pair shape errors

Items must be { k, v } or length-2 arrays. Mixed junk shapes cause aggregation errors.

inverse

Need the reverse?

Use $objectToArray to go from object back to { k, v } pairs.

Performance Notes

ApproachCostBest for
$arrayToObject on a fieldO(pairs) per documentSmall attribute lists
Build pairs with $map firstExtra pass + convertDynamic keys from other fields
Round-trip with $objectToArrayTwo transformsEdit keys, then rebuild object

Conversion is cheap for short attribute arrays. Filter early with $match when only some documents need reshaping.

Key Takeaways

  • Role: pairs array → one object.
  • Formats: {k,v} or [key, value].
  • Keys: must be strings; last duplicate wins.
  • Inverse: $objectToArray.

One line: $arrayToObject turns a list of pairs into a normal document object—pick {k,v} or [key, value].

Frequently Asked Questions

$arrayToObject converts an array of key-value pairs into one object. Each pair becomes a field in the output document shape. Use it inside aggregation stages such as $project and $addFields.
Two formats: documents with k and v fields ({ k: "color", v: "blue" }), or two-element arrays ([ "color", "blue" ]). Keys must be strings.
If the same key appears more than once, the last value wins and overwrites earlier ones.
$objectToArray converts an object into an array of { k, v } pairs. The two operators are inverses.
Keys must resolve to strings. Non-string keys cause the aggregation to fail.
Yes. Only the key must be a string. Values can be numbers, strings, arrays, documents, or null.

Next: $asin

Compute the inverse sine (arc sine) in an aggregation pipeline.

$asin tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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