- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $arrayToObject (aggregation)
$arrayToObject (aggregation)¶
On this page
Definition¶
-
$arrayToObject¶ Converts an array into a single document; the array must be either:
An array of two-element arrays where the first element is the field name, and the second element is the field value:
- OR -
An array of documents that contains two fields,
kandvwhere:- The
kfield contains the field name. - The
vfield contains the value of the field.
- The
$arrayToObjecthas the following syntax:The
<expression>can be any valid expression that resolves to an array of two-element arrays or array of documents that contains “k” and “v” fields.For more information on expressions, see Expressions.
Behavior¶
If the name of a field repeats in the array,
- Starting in 4.0.5,
$arrayToObjectuses the last value for that field. For 4.0.0-4.0.4, the value used depends on the driver. - Starting in 3.6.10,
$arrayToObjectuses the last value for that field. For 3.6.0-3.6.9, the value used depends on the driver. - Starting in 3.4.19,
$arrayToObjectuses the last value for that field. For 3.4.0-3.4.19, the value uses depends on the driver.
| Example | Results |
|---|---|
|
Starting in versions 4.0.5+ (3.6.10+ and 3.4.19+), if the name
of a field repeats in the array, |
Examples¶
$arrayToObject Example¶
Consider a inventory collection with the following documents:
The following aggregation pipeline operation use the
$arrayToObject to return the dimensions field as a
document:
The operation returns the following:
Starting in versions 4.0.5+ (3.6.10+ and 3.4.19+), if the name of a
field repeats in the array, $arrayToObject uses the last
value for that field.
$objectToArray + $arrayToObject Example¶
Consider a inventory collection with the following documents:
The following aggregation pipeline operation calculates the total in
stock for each item and adds to the instock document:
The operation returns the following:
See also