Back to top

ReQL command: merge

Command syntax

singleSelection.merge([object | function, object | function, ...]) → object

object.merge([object | function, object | function, ...]) → object

sequence.merge([object | function, object | function, ...]) → stream

array.merge([object | function, object | function, ...]) → array

Description

Merge two or more objects together to construct a new object with properties from all. When there is a conflict between field names, preference is given to fields in the rightmost object in the argument list. merge also accepts a subquery function that returns an object, which will be used similarly to a map function.

Example: Equip Thor for battle.

r.table('marvel').get('thor').merge( r.table('equipment').get('hammer'), r.table('equipment').get('pimento_sandwich') ).run(conn, callback) 

Example: Equip every hero for battle, using a subquery function to retrieve their weapons.

r.table('marvel').merge(function (hero) { return { weapons: r.table('weapons').get(hero('weaponId')) }; }).run(conn, callback) 

Example: Use merge to join each blog post with its comments.

Note that the sequence being merged—in this example, the comments—must be coerced from a selection to an array. Without coerceTo the operation will throw an error (“Expected type DATUM but found SELECTION”).

r.table('posts').merge(function (post) { return { comments: r.table('comments').getAll(post('id'), {index: 'postId'}).coerceTo('array') } }).run(conn, callback) 

Example: Merge can be used recursively to modify object within objects.

r.expr({weapons : {spectacular_graviton_beam : {dmg : 10, cooldown : 20}}}).merge( {weapons : {spectacular_graviton_beam : {dmg : 10}}}).run(conn, callback) 

Example: To replace a nested object with another object you can use the literal keyword.

r.expr({weapons : {spectacular_graviton_beam : {dmg : 10, cooldown : 20}}}).merge( {weapons : r.literal({repulsor_rays : {dmg : 3, cooldown : 0}})}).run(conn, callback) 

Example: Literal can be used to remove keys from an object as well.

r.expr({weapons : {spectacular_graviton_beam : {dmg : 10, cooldown : 20}}}).merge( {weapons : {spectacular_graviton_beam : r.literal()}}).run(conn, callback) 

Get more help

Couldn't find what you were looking for?