Search code examples
javamongodbclonedocumentbson

How to make a clone of a BSON Document (similar to Json)?


For my project, I will be creating a new BSON Document (for MongoDB) when a new user signs up, however, instead of creating a new BSON Document and appending all the default values for EVERY new user (e.g. creating a new document, appending 0 to all the statistics, e.g. playtime, kills, deaths, wins, losses), I decided to create a Document template, that contains all these default values, with the hope to clone the template and insert the new users name, id and address - this would be more efficient.

private static Document getDefaultPlayerDocument() {
    Document player = new Document();
    player.append(DBKey.PLAYTIME.getKey(), 0);
    player.append(DBKey.LASTSEEN.getKey(), "Online");
    player.append(DBKey.RANK.getKey(), Group.DEFAULT.asString());
    player.append(DBKey.EXPIRY.getKey(), "null");
    player.append(DBKey.KILLS.getKey(), 0);
    player.append(DBKey.DEATHS.getKey(), 0);
    player.append(DBKey.WINS.getKey(), 0);
    player.append(DBKey.LOSSES.getKey(), 0);
    player.append(DBKey.SCORE.getKey(), 0);
    return player;
}

Here is the code to create the default document, which is stored.

However, I am looking for a method to CLONE this document when I want to, e.g.

New user joins with ID:5, called Archie, a clone of the template is created, the name is changed to Archie and Id changed to 5.

I have tried looking at .clone() methods but doesn't seem to exist.

Any help?


Solution

  • For a simple document (like your example) just create a new Document using the Document(Map<String, Object>) constructor, as Document happens to be derived from Map.

    Document clonedDoc = new Document(originalDoc);
    

    Note however, that this will only create a new "first level" where all existing sub-documents will be the same object, i.e. not a copy of the original sub-document.

    The most simple way to deep-clone is encoding to json and parsing from there:

    Document clonedDoc = Document.parse(originalDoc.toJson());