How to remove a key from a RethinkDB document?
Asked Answered
A

3

47

I'm trying to remove a key from a RethinkDB document. My approaches (which didn't work):

r.db('db').table('user').replace(function(row){delete row["key"]; return row}) 

Other approach:

r.db('db').table('user').update({key: null}) 

This one just sets row.key = null (which looks reasonable).

Examples tested on rethinkdb data explorer through web UI.

Aniela answered 2/9, 2013 at 20:31 Comment(0)
A
86

Here's the relevant example from the documentation on RethinkDB's website: http://rethinkdb.com/docs/cookbook/python/#removing-a-field-from-a-document

To remove a field from all documents in a table, you need to use replace to update the document to not include the desired field (using without):

r.db('db').table('user').replace(r.row.without('key'))

To remove the field from one specific document in the table:

r.db('db').table('user').get('id').replace(r.row.without('key'))

You can change the selection of documents to update by using any of the selectors in the API (http://rethinkdb.com/api/), e.g. db, table, get, get_all, between, filter.

Antetype answered 2/9, 2013 at 20:46 Comment(4)
If you are looking for the javascript version of the recipe: rethinkdb.com/docs/cookbook/javascript/…Lomax
How can I do this for nested field of key?Gutenberg
@Suvitruf, you can use the nested field syntax as follows: .replace(r.row.without({key1: {key2: true}}))Misrepresent
How do I delete a nested property? like without('foo.bar.baz') to delete the baz property?Hort
F
12

You can use replace with without:

r.db('db').table('user').replace(r.row.without('key'))
Formulate answered 2/9, 2013 at 20:41 Comment(4)
How can I do this for nested field of key?Gutenberg
For nested fields, you can use the nested field syntax as follows: .replace(r.row.without({key1: {key2: true}}))Misrepresent
How do I combine this with also updating the value of another key?Aisne
What does the true do here?Hort
S
6

You do not need to use replace to update the entire document. Here is the relevant documentation: ReQL command: literal

Assume your user document looks like this:

{
  "id": 1,
  "name": "Alice",
  "data": {
    "age": 19,
    "city": "Dallas",
    "job": "Engineer"
  }
}

And you want to remove age from the data property. Normally, update will just merge your new data with the old data. r.literal can be used to treat the data object as a single unit.

r.table('users').get(1).update({ data: r.literal({ age: 19, job: 'Engineer' }) }).run(conn, callback)

// Result passed to callback
{
  "id": 1,
  "name": "Alice",
  "data": {
    "age": 19,
    "job": "Engineer"
  }
}

or

r.table('users').get(1).update({ data: { city: r.literal() } }).run(conn, callback)

// Result passed to callback
{
  "id": 1,
  "name": "Alice",
  "data": {
    "age": 19,
    "job": "Engineer"
  }
}
Sweeny answered 28/6, 2017 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.