MongoDB $objectToArray Operator

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

What Is $objectToArray?

$objectToArray is a MongoDB aggregation expression that turns an object into an array of { k, v } pairs—one element per top-level field. It is the inverse of $arrayToObject.

Remember
$objectToArray = object → [ { k, v }, ... ]

{ $objectToArray: <objectExpression> }

input:
  { theme: "dark", lang: "en" }

output:
  [
    { k: "theme", v: "dark" },
    { k: "lang",  v: "en" }
  ]

k → field name (string)
v → field value
top-level only (not recursive)
null / missing → null
NeedPrefer
Object → array of pairs$objectToArray
Array of pairs → object$arrayToObject
One doc per pair$objectToArray + $unwind

How to Use $objectToArray in MongoDB

Point at an embedded object field, convert it to pairs, then optionally unwind.

  1. Choose an expression stage ($addFields or $project).
  2. Write { $objectToArray: "$settings" }.
  3. Read each pair as k (key) and v (value).
  4. Optionally $unwind the array for one document per field.
PieceRequired?Role
Object expressionYesDocument / embedded object to convert
Result—Array of { k, v } documents

Pseudocode

Pseudocode
obj = evaluate(objectExpression)
if obj is null or missing:
    result = null
else:
    result = []
    for each top-level field in obj:
        append { k: fieldName, v: fieldValue }
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting objects to arrays.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $objectToArray: "$settings" }
Output shape[ { k: "...", v: ... }, ... ]
DepthTop-level fields only
Inverse$arrayToObject
Sample check{ a: 1 } → [ { k: "a", v: 1 } ]

Live Preview

Watch $objectToArray turn a small object into { k, v } pairs.

Simulates { $objectToArray: object } (same idea as the mongosh examples below).

Result
input:
  { theme: "dark", lang: "en" }

$objectToArray →
  [
    { k: "theme", v: "dark" },
    { k: "lang", v: "en" }
  ]

Worked Walkthrough — Settings Object

A user has settings: { theme: "dark", lang: "en" }. We want an array of pairs.

Calculation
Object:
  { theme: "dark", lang: "en" }

Field by field:
  theme → { k: "theme", v: "dark" }
  lang  → { k: "lang",  v: "en" }

$objectToArray result:
  [
    { k: "theme", v: "dark" },
    { k: "lang",  v: "en" }
  ]

MongoDB Examples

We use one user document with a settings object. First we store it, then we convert to pairs, then we unwind to one document per setting. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one user named Asha with settings theme: dark and lang: en.

mongosh
db.users.insertOne({
  _id: 1,
  name: "Asha",
  settings: {
    theme: "dark",
    lang: "en"
  }
});

How the Data Is Stored in MongoDB

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

mongosh
db.users.find()

Read that document like this:

Field in MongoDBValuePlain English
name"Asha"User name
settingsobject with 2 fieldsEmbedded preferences object
Picture
settings object          $objectToArray
─────────────────        ─────────────────────────
theme: "dark"    →       { k: "theme", v: "dark" }
lang:  "en"      →       { k: "lang",  v: "en" }

How It Works

  1. Insert once. insertOne adds a single user document to users.
  2. Store an embedded object. settings is exactly what $objectToArray expects.
  3. find() shows the same shape. Ready for conversion next.

Example 2 — Convert to Pairs

Goal: add a pairs field with the settings as an array of { k, v } documents.

mongosh
db.users.aggregate([
  {
    $addFields: {
      pairs: { $objectToArray: "$settings" }
    }
  }
]);

How It Works

  1. Read the object. "$settings" points at the embedded document.
  2. One pair per field. theme and lang each become a { k, v } element.
  3. Keep the original. $addFields adds pairs without deleting settings.

Example 3 — Unwind Pairs

Goal: one output document per setting key (useful for reporting).

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      pairs: { $objectToArray: "$settings" }
    }
  },
  { $unwind: "$pairs" },
  {
    $project: {
      name: 1,
      key: "$pairs.k",
      value: "$pairs.v"
    }
  }
]);

How It Works

  1. Convert first. Same $objectToArray as Example 2.
  2. Unwind the array. $unwind makes one document per pair.
  3. Lift k and v. Project key and value for a flat, readable shape.
  4. Same _id. Both rows still belong to Asha.

Edge Cases & Pitfalls

Check these before using $objectToArray in production pipelines.

depth

Not recursive

Nested objects stay inside v. Convert nested fields with another $objectToArray if you need deeper pairs.

type

Input must be an object

Arrays, numbers, and strings are not valid inputs. Pass a document or embedded object field.

null

Null or missing → null

Missing fields return null, not []. Guard before $unwind if needed.

order

Field order can vary

Do not rely on a fixed array order for business logic. Filter or sort by k when order matters.

Performance Notes

ApproachCostBest for
$objectToArray aloneCheap per documentSmall embedded objects
+ $unwindMore output docsPer-key reporting / grouping
Huge objectsLarge arraysPrefer leaner schemas when possible

Converting a small settings-style object is inexpensive. Unwinding multiplies document count—filter early when you only need some keys.

Key Takeaways

  • Role: object → array of { k, v } pairs.
  • Syntax: { $objectToArray: "$field" }.
  • Shape: k = key, v = value (top-level only).
  • Inverse: $arrayToObject rebuilds the object.

One line: $objectToArray answers “what are this object’s fields as a list of key/value pairs?”

Frequently Asked Questions

$objectToArray converts an object into an array of key-value pairs. Each field becomes { k: "fieldName", v: value }. It is the inverse of $arrayToObject. Use it inside aggregation stages such as $project and $addFields.
The syntax is { $objectToArray: <objectExpression> }. Pass a field path like "$settings" or any expression that resolves to a document object.
An array of documents with k (string key) and v (value). For example, { theme: "dark", lang: "en" } becomes [ { k: "theme", v: "dark" }, { k: "lang", v: "en" } ].
No. It only converts top-level fields of the argument. Nested objects appear as the v value unchanged.
Yes. Convert the object to an array, then $unwind 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.

Next: $or

Match documents when any of several conditions is true.

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