Gary Sieling

RethinkDB: coalesce example

In SQL, the coalesce or NVL function takes null values and replaces them with a defined value.

To replicate this in RethinkDB, you can use the ‘branch’ function to test for null and remove it:

r.db('test')
 .table('users')
 .map(
   (doc) => { 
     return
       {
         first_name: null
       }
   }
 ).map( 
   (doc) => {
     return {
       first_name: 
         r.branch(
           doc('first_name').eq(null), 
           'no name', 
           doc('first_name')  
         )
     }
   }
 )

If you are stuck instead with undefined values, you can instead merge in values for these columns:

r.db('test').table('users')
  .map(
    (doc) => { return r.expr(
      {
        first_name: '',
        last_name: ''
      }
    ).merge(doc) }
  )
Exit mobile version