upsert for filters
Signature
> upsert {flags} (field) (replacement value)
Parameters
field: The name of the column to update or insert.replacement value: The new value to give the cell(s), or a closure to create the value.
Input/output types:
| input | output |
|---|---|
| record | record |
| table | table |
| list<any> | list<any> |
Examples
Update a record's value
> {'name': 'nu', 'stars': 5} | upsert name 'Nushell'
╭───────┬─────────╮
│ name │ Nushell │
│ stars │ 5 │
╰───────┴─────────╯Insert a new entry into a record
> {'name': 'nu', 'stars': 5} | upsert language 'Rust'
╭──────────┬──────╮
│ name │ nu │
│ stars │ 5 │
│ language │ Rust │
╰──────────┴──────╯Update each row of a table
> [[name lang]; [Nushell ''] [Reedline '']] | upsert lang 'Rust'
╭───┬──────────┬──────╮
│ # │ name │ lang │
├───┼──────────┼──────┤
│ 0 │ Nushell │ Rust │
│ 1 │ Reedline │ Rust │
╰───┴──────────┴──────╯Insert a new column with values computed based off the other columns
> [[foo]; [7] [8] [9]] | upsert bar {|row| $row.foo * 2 }
╭───┬─────┬─────╮
│ # │ foo │ bar │
├───┼─────┼─────┤
│ 0 │ 7 │ 14 │
│ 1 │ 8 │ 16 │
│ 2 │ 9 │ 18 │
╰───┴─────┴─────╯Update null values in a column to a default value
> [[foo]; [2] [null] [4]] | upsert foo { default 0 }
╭───┬─────╮
│ # │ foo │
├───┼─────┤
│ 0 │ 2 │
│ 1 │ 0 │
│ 2 │ 4 │
╰───┴─────╯Upsert into a list, updating an existing value at an index
> [1 2 3] | upsert 0 2
╭───┬───╮
│ 0 │ 2 │
│ 1 │ 2 │
│ 2 │ 3 │
╰───┴───╯Upsert into a list, inserting a new value at the end
> [1 2 3] | upsert 3 4
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
╰───┴───╯Upsert into a nested path, creating new values as needed
> [{} {a: [{}]}] | upsert a.0.b "value"
╭───┬───────────────╮
│ # │ a │
├───┼───────────────┤
│ 0 │ ╭───┬───────╮ │
│ │ │ # │ b │ │
│ │ ├───┼───────┤ │
│ │ │ 0 │ value │ │
│ │ ╰───┴───────╯ │
│ 1 │ ╭───┬───────╮ │
│ │ │ # │ b │ │
│ │ ├───┼───────┤ │
│ │ │ 0 │ value │ │
│ │ ╰───┴───────╯ │
╰───┴───────────────╯Notes
When updating or inserting a column, the closure will be run for each row, and the current row will be passed as the first argument. Referencing $in inside the closure will provide the value at the column for the current row or null if the column does not exist.
When updating a specific index, the closure will instead be run once. The first argument to the closure and the $in value will both be the current value at the index. If the command is inserting at the end of a list or table, then both of these values will be null.