Examples: Updating JSON Documents

This section contains sample code that updates a JSON document in a MapR-DB JSON table using an OJAI mutation. It also shows the MapR-DB Shell syntax for updating documents.

See Using OJAI Mutation Syntax for more details about OJAI mutations.

The following code is available at OJAI_012_UpdateDocument.java. It does the following:

 * Copyright (c) 2017 MapR, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.
package com.mapr.ojai.examples;

import org.ojai.store.Connection;
import org.ojai.store.DocumentMutation;
import org.ojai.store.DocumentStore;
import org.ojai.store.DriverManager;

public class OJAI_012_UpdateDocument {

  public static void main(String[] args) {

    System.out.println("==== Start Application ===");

    // Create an OJAI connection to MapR cluster
    final Connection connection = DriverManager.getConnection("ojai:mapr:");

    // Get an instance of OJAI DocumentStore
    final DocumentStore store = connection.getStore("/demo_table");

    String docId = "user0002";

    // Print the document before update
    System.out.println( "\t"+ store.findById(docId).getMap("address").toString() );

    // Create a DocumentMutation to update the zipCode field
    DocumentMutation mutation = connection.newMutation()
        .set("address.zipCode", 95196L);

    System.out.println("\tUpdating document "+ docId);

    // Update the Document with '_id' = "user0002"
    store.update(docId, mutation);

    // Print the document after update
    System.out.println( "\t"+ store.findById(docId).getMap("address").toString() );

    // Close this instance of OJAI DocumentStore

    // close the OJAI connection and release any resources held by the connection

    System.out.println("==== End Application ===");


The following dbshell command is equivalent to the code example. See dbshell update for more information and examples.

# mapr dbshell
maprdb root:> update /demo_table --id user002 --m {"$set":{"address.zipCode":95196}}