$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.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $objectToArray: <object> }
⚙️ Parameters
| object | The 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
- Each result element has k as the string field name and v as the field value
- Only plain documents convert; arrays or scalars throw
- Field order follows insertion order; pair with $map/$filter to handle dynamic fields
🏷️ Related Tags
💡 Related Cases
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.