$objectToArray (Convert Object to Array of Key-Value Pairs)

Last updated: 2026-10-09

$objectToArray (Convert Object to Array of Key-Value Pairs)

$objectToArray converts a document into an array of key-value pairs, each element shaped like { k: 'fieldName', v: 'fieldValue' }. It shines when field names are dynamic (e.g., per-user score dimensions) by letting $map/$filter process every field uniformly, and is also handy for flattening subdocuments before aggregation. The argument must be a plain document — an array throws. Pair it with $arrayToObject for round-trip conversion.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $objectToArray: <object> }

⚙️ Parameters

objectThe document (BSON object) expression to convert.

Returns:An array of key-value pairs shaped { k: 'fieldName', v: 'value' }; null when the argument is null

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $objectToArray: turn a score subdocument into an array
db.users.aggregate([
  { $project: {
      scores: { $objectToArray: '$scores' }
  } }
])

Output:

{ '_id': 1, 'scores': [ { 'k': 'math', 'v': 90 }, { 'k': 'eng', 'v': 85 } ] }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow do I handle dynamic field names uniformly?
AConvert with $objectToArray first, process with $map/$filter, then convert back with $arrayToObject.
QCan it convert an array?
ANo, the argument must be a document; arrays throw.
QIs field order preserved?
AYes, the insertion order is kept.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏