Skip to content

Instantly share code, notes, and snippets.

@kharioki
Last active September 17, 2021 16:31
Show Gist options
  • Save kharioki/8a3764aba923dabb91b79bb9927c4636 to your computer and use it in GitHub Desktop.
Save kharioki/8a3764aba923dabb91b79bb9927c4636 to your computer and use it in GitHub Desktop.
A RethinkDB cheatsheet.

RethinkDB Cheat Sheet

Create database

r.dbCreate('mydb')

List databases

r.dbList()

Drop database

r.dbDrop('test')

Create table

r.db('mydb').tableCreate('users')

Delete table

r.db('mydb').table("test").delete()

Insert record

r.db('mydb').table('users').insert({
		name: 'Tony Stark',
		city: 'Westlands',
		age: 30
	}
)

Insert records (Array or object)

r.db('mydb').table('users').insert([
		{name: 'Tony Stark', city: 'Westlands', age: 30},
		{name: 'Tessie Waithira', city: 'Nairobi', age: 28},
		{name: 'Ken Smith', city: 'Nakuru', age: 30},
		{name: 'Stella Williams', city: 'Westlands', age: 31}
])

Get records

r.db('mydb').table('users')

Filter records

r.db('mydb').table('users').filter({
		city: 'Westlands'
})

Select specific fields

r.db('mydb').table('users').pluck('name')

Order By

r.db('mydb').table('users').orderBy(r.desc('name'))

Pluck & order by

r.db('mydb').table('users').filter({
	'city': 'Westlands'
}).orderBy(
	r.desc('name')
).pluck('name')

Limit records

r.db('mydb').table('users').limit(2)

Count

r.db('mydb').table("users").count()

Distinct

r.db('mydb').table("users").pluck("city").distinct()

Greater & less than

r.db('mydb').table("users").filter(r.row('age').gt(30))
r.db('mydb').table("users").filter(r.row('age').gte(30))
r.db('mydb').table("users").filter(r.row('age').lt(30))

Update record

r.db('mydb').table("users").filter({
		id: '592502cc-a84e-442d-a45f-24ebc344d8cf'
}).update({
    "city": 'Nairobi'
})

Delete record

r.db('mydb').table("users").filter({
		id: '592502cc-a84e-442d-a45f-24ebc344d8cf'
}).delete()

Joins

Create and insert data for second table

r.db('mydb').table('todos')
r.db('mydb').table('todos').insert([
  {user_id: '904e926f-d864-4cdd-a560-88750898f15e', text: 'Buy groceries'},
  {user_id: '2ce7e4d3-3dd1-4ca5-8bf6-e81664b88e5b', text: 'Take exams'},
  {user_id: '1b33ed51-778c-40a2-b572-bb71d7a0d36d', text: 'Do laundry'},
  {user_id: '3303d961-48ed-41d5-ac04-e824f5e729d1', text: 'Buy shopping'},
  {user_id: 'a049fc6b-474a-483f-96db-329fe298b9af', text: 'Water plants'},
  {user_id: '3303d961-48ed-41d5-ac04-e824f5e729d1', text: 'Fix laptop'}
])

Join tables

r.db('mydb').table("todos").eqJoin("user_id", r.db('mydb').table("users")).zip()

zip() will merge the user in the task, overwriting fields in case of conflict

r.db('mydb').table("todos").eqJoin("user_id", r.db('mydb').table("users")).zip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment