explode - Convert N array elements into N documents
The explode
command explodes an array of N elements into N documents, each containing one element of the array in the specified keypath.
Syntax
NOTE: The default behaviour is discard
(see next section for how this works)
Preserve or discard
As part of the explode
operation, users can declare what they would like to do with the original document's fields. For example, consider the following document:
If we run the following command:
Then the new documents will look like this. Note that the original id
field and my_arr
is now gone:
However, if we were to run the following command:
Then the resultant documents would look like this, with the original my_arr
and id
values intact:
{
"arr_element": "a",
"id": 10,
"my_arr": ["a", "b", "c"]
},
{
"arr_element": "b",
"id": 10,
"my_arr": ["a", "b", "c"]
},
{
"arr_element": "c",
"id": 10,
"my_arr": ["a", "b", "c"]
}
NOTE: If an exploded value matches a keypath of an existing value in the original document, the exploded value takes priority, meaning it overwrites the value in the original document.
NOTE: When preserving original fields, if the destination keypath already exists, it will be overwritten with an exploded value.
Example - Showing all user permissions
Consider the following documents:
I want to render these so that each document represents an individual permission, rather than constantly performing array operations. We can do this using explode
:
This will result in the following documents:
{ "userid": "1", "scope": "read", "scopes": ["read", "write"]}
{ "userid": "1", "scope": "write", "scopes": ["read", "write"]}
{ "userid": "2", "scope": "read", "scopes": ["read", null]}
{ "userid": "2", "scope": null, "scopes": ["read", null]}