# `explode`

## Description

The `explode` command transforms an array of *N* elements into *N* separate documents, each containing one element of the array at the specified keypath. It’s commonly used to “flatten” nested data structures for easier analysis or aggregation.

When using `explode`, you can control whether to keep or remove the original document fields via the `original` modifier:

- `original discard` removes all original fields, producing minimal output with just the exploded key.
- `original preserve` retains the original document fields, duplicating them across the new documents.

Note

If the destination keypath already exists in the document, it is overwritten by the exploded value.\
The default behavior is `original discard`.

## Syntax

```dataprime
explode <expression> into <keypath> [original discard|preserve]
```

## Example

**Use case: Represent each user permission as an individual document**

Each log contains a list of permissions (`scopes`) assigned to a user. To make permission-level analysis simpler, we can use `explode` to create one document per permission, preserving the original fields for context.

### Example data

```json
{ "userid": "1", "scopes": ["read", "write"] },
{ "userid": "2", "scopes": ["read", null] }
```

### Example query

```dataprime
source logs | explode scopes into scope original preserve
```

### Example output

```json
{ "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] }
```

The `explode` command expands each array element into its own document while keeping the original `userid` and `scopes` fields. This makes it easier to query and aggregate user permissions individually. id: explode
