Search code examples
pythondatabasenosqlcouchbasesql++

When i move document betwen couchbase collections, how do i add time of moving?


I have collection with some documents. Sometimes i need to move certain document to another collection (aka archive) and i also need to add archiving time to it. Now i do it in two queries, but want to reduce to one.

Due to lack of experiense in NoSQL, it`s hard to me to make any assumption, so i am asking for help.

query = f"""INSERT INTO bucket.scope.second_collection (KEY key_id, VALUE document)
            SELECT META(doc).id AS key_id, doc AS document
            FROM bucket.scope.first_collection AS doc
            WHERE id = {};"""
cluster.query(query, QueryOptions(positional_parameters=[]))

time = datetime.now(tz)
query = f"""UPDATE bucket.scope.second_collection
            SET date_of_moving = "{time}"
            WHERE id = "{}";"""
cluster.query(query, QueryOptions(positional_parameters=[]))

Solution

  • You can use OBJECT_ADD() to add additional fields to an existing JSON object.

    I'm no Python dev, so pardon if I get some syntax wrong, but here's an example of OBJECT_ADD:

    query = f"""INSERT INTO bucket.scope.second_collection (KEY key_id, VALUE document)
                SELECT META(doc).id AS key_id, OBJECT_ADD(doc, ""date_of_moving"", {time}) AS document
                FROM bucket.scope.first_collection AS doc
                WHERE id = {};"""