$objectToArray
Converts an object to an array of key-value pairs, where each element is a document with 'k' (key) and 'v' (value) fields.
Syntax
{ $objectToArray: <object_expression> }
Parameters
object_expression
objectrequiredExpression that resolves to an object to be converted to array format
Examples
Convert object to array
Transform object fields into key-value pair array
Query:
db.products.aggregate([{ $project: { items: { $objectToArray: "$inventory" } } }])
Output:
Document with items array containing k/v pairs from inventory object
Process object fields dynamically
Convert object to array for dynamic field processing
Query:
db.products.aggregate([{ $project: { pairs: { $objectToArray: "$attributes" } } }, { $unwind: "$pairs" }, { $match: { "pairs.v": { $gt: 100 } } }])
Output:
Documents with attribute pairs where values are greater than 100