$objectToArray (aggregation)
On this page
Definition
-
$objectToArray
-
New in version 3.4.4.
Converts a document to an array. The return array contains an element for each field/value pair in the original document. Each element in the return array is a document that contains two fields
k
andv
:- The
k
field contains the field name in the original document. - The
v
field contains the value of the field in the original document.
$objectToArray
has the following syntax:The
<object>
expression can be any valid expression as long as it resolves to a document object.$objectToArray
applies to the top-level fields of its argument. If the argument is a document that itself contains embedded document fields, the$objectToArray
does not recursively apply to the embedded document fields.For more information on expressions, see Expressions.
- The
Examples
$objectToArray
Example
Consider a inventory
collection with the following documents:
The following aggregation pipeline operation use the $objectToArray
to return the dimensions
field as an array:
The operation returns the following:
$objectToArray
to Sum Nested Fields
Consider a inventory
collection with the following documents:
The following aggregation pipeline operation uses the $objectToArray
along with $unwind
and $group
to calculate the total items in stock per warehouse.
The operation returns the following: