Search code examples
jsonnode.jsmongodbrethinkdbjson-patch

Is RethinkDB useful on partial updating json documents according rfc6902?


Please share your experience with partial updating of JSON document.At now I'm storing my JSON documents in MongoDB which looks like the following:

{
  id: ObjectId(507f191e810c19729de860ea),
  title: 'Sterling Archer',    
  comments: [
    {text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']},
    {text: 'Comment test', tags: ['tag2', 'tag5']}
  ]  
}

I need to frequently update my documents by using rfc6902 specification. Now, I do it not optimized way that looks the following (I use nodejs/express/mongoose and fast-json-patch module in this example):

var jsonpatch = require('fast-json-patch');

app.patch('/document/:id', function (req, res, next) {
   var document_id = req.params.id;

   // req.body.patch: { "op": "add", "path": "/comments/2", "value":  {text: 'Comment test3', tags: ['tag4']}" }
   var patches = req.body.patch; 

   // find document
   Document.findById(document_id, function (err, document) {
       // Applying patches
       jsonpatch.apply(document, patches);

       // Update whole document in MongoDB
       Document.update({_id: document_id}, document, function (err) {
           return res.status(200).send(); 
       });
   });
});

This is not optimize approach to patch documents due two queries in MongoDB and replacing whole document. So I'm looking for optimized approach and want to try RethinkDB for this task. Can you help me to inspect possibility of atomic document updating by using single query with RethinkDB? Or should I looks for another way of resolving my problem?

Please share your experience with partial updating of JSON document.


Solution

  • You just need one query in RethinkDB. Suppose you want to update the document whose id is 1 with the values {foo: 1, bar: 2}, and increment the field "count", you would do

    r.table("data").get(1).update(function(doc) {
        return doc.merge({foo: 1, bar:2, count: doc("count").add(1) })
    })
    

    While this update requires a unique query, the whole document will be updated. If you have big documents, you can split them in multiple tables and perform joins later to retrieve the data. You may be interested in reading this article about data modeling: http://www.rethinkdb.com/docs/data-modeling/