How to Upsert in RethinkDB

February 09, 2017 — Daniel Holmes

This is a quick late night post to document one of the things I searched for a few hours on the goog for.

From Mongo's Upsert to Rethink

The first thing you might be here to know is how you can do something like MongoDb's upsert in Rethink. That's a pretty easy one:

r.db("Foo").table("Bar").get("someid").update({"foo": "bar"})

But then the question becomes, how do I find a document by a non index and update that?

Not as easy unfortunately. You see rethink has no concept of unique secondary indexes and that means that an upsert is impossible with anything other than the primary key.

The way around this issue is to use a compound primary key, where you make the primary key an array of values which combined form a unique key.

Unfortunately that's the only way around it for now, so to do the upsert you need to:

r.db("Foo").table("Bar").get(["someid", "somethingelse"]).insert({"foo": "bar"}, {"conflict":"update"})

That's pretty much all their is to it!

Reposted from Dan's Personal Blog