---
title: "Update"
description: "Learn how to update nested JSON documents in Aerospike using the Java client and Collection Data Types (CDT)."
---

# Update

> For the complete documentation index see: [llms.txt](https://aerospike.com/docs/llms.txt)
> 
> All documentation pages available in markdown.

Jump to the [Code block](#code-block) for a combined complete example.

## Create a document record

The following example demonstrates how to read a document record with a JSON helper library. In Aerospike, JSON documents are handled as a [Collection Data Type (CDT)](https://aerospike.com/docs/develop/data-types/collections). A JSON object is equivalent to a [map](https://aerospike.com/docs/develop/data-types/collections/map), and a JSON array is equivalent to a [list](https://aerospike.com/docs/develop/data-types/collections/list).

This example creates the following JSON document:

```json
"sightings": [{"sighting":{"occurred":20200912,"reported":20200916,"posted":20201105,"report":{"city":"Kirkland","duration":"~30 minutes","shape":["circle"],"state":"WA","summary":"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area.  Four lights were spotted rotating above the local Safeway and surrounding streets.  They were rotating fast but staying relatively in the same spots.  Also described as orange lights. About thirty minutes later they disappeared.  The second they disappeared the power was restored.  Later a station of police from Woodinville and Kirkland came to guard the street where it happened.  They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway.  The police also would not let people walk past to go home."},"location":"\"{\"type\":\"Point\",\"coordinates\":[-122.1966441,47.69328259]}\""}},

{"sighting":{"occurred":20200322,"reported":20200322,"posted":20200515,"report":{"city":"Pismo Beach","duration":"5 minutes","shape":["light"],"state":"CA","summary":"About 20 solid, bright lights moving at the same altitude, heading and speed.  Spaced perfectly apart flying over the ocean headed south."},"location":"\"{\"type\":\"Point\",\"coordinates\":[-120.6595,35.1546]}\""}},

{"sighting":{"occurred":20200530,"reported":20200531,"posted":20200625,"report":{"city":"New York Staten Island","duration":"2 minutes","shape":["disk"],"state":"NY","summary":"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds."}}}]
```

The JSON document is added to a bin called `sightings` which is of data type [map](https://aerospike.com/docs/develop/data-types/collections/map). There are some advantages to holding an entire document in a single bin, rather than spreading out the document’s fields over multiple bins. There is less metadata overhead when namespaces contain fewer, larger bins.

### Setup

Import the necessary helpers, create a client connection, and create a key.

```java
import com.aerospike.client.*;

import com.aerospike.client.Record;

import com.aerospike.client.cdt.*;

import com.aerospike.client.policy.RecordExistsAction;

import com.aerospike.client.policy.WritePolicy;

import com.google.gson.Gson;

import java.util.HashMap;

import java.util.Map;

AerospikeClient client = new AerospikeClient("localhost", 3000);

// Aerospike namespace, set, and key_id to be used for the Aerospike key

String namespace = "sandbox";

String set = "ufo";

int key_id = 5001;

String binName = "sightings";

// Define Aerospike key

Key key = new Key(namespace, set, key_id);
```

Prepare the JSON document to be sent to Aerospike.

```java
// Example JSON string

String sightings =

        "[{\"sighting\":{\"occurred\":20200912,\"reported\":20200916,\"posted\":20201105,\"report\":{\"city\":\"Kirkland\",\"duration\":\"~30 minutes\",\"shape\":[\"circle\"],\"state\":\"WA\",\"summary\":\"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area.  Four lights were spotted rotating above the local Safeway and surrounding streets.  They were rotating fast but staying relatively in the same spots.  Also described as orange lights. About thirty minutes later they disappeared.  The second they disappeared the power was restored.  Later a station of police from Woodinville and Kirkland came to guard the street where it happened.  They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway.  The police also would not let people walk past to go home.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-122.1966441,47.69328259]}\\\"\"}},\n" +

        "{\"sighting\":{\"occurred\":20200322,\"reported\":20200322,\"posted\":20200515,\"report\":{\"city\":\"Pismo Beach\",\"duration\":\"5 minutes\",\"shape\":[\"light\"],\"state\":\"CA\",\"summary\":\"About 20 solid, bright lights moving at the same altitude, heading and speed.  Spaced perfectly apart flying over the ocean headed south.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-120.6595,35.1546]}\\\"\"}},\n" +

        "{\"sighting\":{\"occurred\":20200530,\"reported\":20200531,\"posted\":20200625,\"report\":{\"city\":\"New York Staten Island\",\"duration\":\"2 minutes\",\"shape\":[\"disk\"],\"state\":\"NY\",\"summary\":\"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds.\"}}}]";

// Convert string to Java Map

List<Map<String, Object>> sightingMap = new Gson().fromJson(sightings, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());

// Set an Aerospike bin with the bin name "sightings" and put the JSON document in as a map

Bin bin = new Bin(binName, Value.get(sightingMap));
```

### Write

Write the document to Aerospike.

```java
// Create the write policy

WritePolicy writePolicy = new WritePolicy();

writePolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;

// Write the record to Aerospike

try {

    client.delete(null, key);

    client.put(writePolicy, key, bin);

    Record record = client.get(null, key);

    Object value = record.getValue(binName);

    System.out.printf("Create succeeded \nKey: %d \nRecord: %s\n", key.userKey.toLong(), new Gson().toJson(value));

}

catch (AerospikeException ae) {

    System.out.printf("Create failed\nError: %s\n", ae.getMessage());

}
```

### Update

Update the newly created document.

```java
// Create the update policy

WritePolicy updatePolicy = new WritePolicy();

updatePolicy.recordExistsAction = RecordExistsAction.UPDATE;

// Update the record written to Aerospike in step before

try {

    // Update the sighting city in the first record in list of "sightings" from "Kirkland" to "Seattle"

    client.operate(updatePolicy, key,

            MapOperation.put(

                    new MapPolicy(MapOrder.KEY_VALUE_ORDERED, MapWriteMode.UPDATE),

                    binName, // Bin to be updated

                    Value.get("city"), // Key to be updated

                    Value.get("Seattle"), // Update value

                    CTX.listIndex(0), CTX.mapKey(Value.get("sighting")), CTX.mapKey(Value.get("report")))

    );

}

catch (AerospikeException ae) {

    System.out.printf("Update failed\nError: %s\n", ae.getMessage());

}
```

### Read

Read the updated document.

```java
// Read updated record

Record record = client.get(null, key);

Object value = record.getValue(binName);

System.out.printf("Read succeeded \nKey: %d \nRecord: %s\n", key.userKey.toLong(), new Gson().toJson(value));

// Close the client

client.close();
```

## Code block

Expand this section for a single code block to update a document record.

```java
import com.aerospike.client.*;

import com.aerospike.client.Record;

import com.aerospike.client.cdt.*;

import com.aerospike.client.policy.RecordExistsAction;

import com.aerospike.client.policy.WritePolicy;

import com.google.gson.Gson;

import java.util.HashMap;

import java.util.Map;

AerospikeClient client = new AerospikeClient("localhost", 3000);

// Aerospike namespace, set, and key_id to be used for the Aerospike key

String namespace = "sandbox";

String set = "ufo";

int key_id = 5001;

String binName = "sightings";

// Define Aerospike key

Key key = new Key(namespace, set, key_id);

// Example JSON string

String sightings =

        "[{\"sighting\":{\"occurred\":20200912,\"reported\":20200916,\"posted\":20201105,\"report\":{\"city\":\"Kirkland\",\"duration\":\"~30 minutes\",\"shape\":[\"circle\"],\"state\":\"WA\",\"summary\":\"4 rotating orange lights in the Kingsgate area above the Safeway. Around 9pm the power went out in the Kingsgate area.  Four lights were spotted rotating above the local Safeway and surrounding streets.  They were rotating fast but staying relatively in the same spots.  Also described as orange lights. About thirty minutes later they disappeared.  The second they disappeared the power was restored.  Later a station of police from Woodinville and Kirkland came to guard the street where it happened.  They wouldn't let anyone go past the street, putting out search lights and flare signals so people couldn't drive past Safeway.  The police also would not let people walk past to go home.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-122.1966441,47.69328259]}\\\"\"}},\n" +

        "{\"sighting\":{\"occurred\":20200322,\"reported\":20200322,\"posted\":20200515,\"report\":{\"city\":\"Pismo Beach\",\"duration\":\"5 minutes\",\"shape\":[\"light\"],\"state\":\"CA\",\"summary\":\"About 20 solid, bright lights moving at the same altitude, heading and speed.  Spaced perfectly apart flying over the ocean headed south.\"},\"location\":\"\\\"{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\":[-120.6595,35.1546]}\\\"\"}},\n" +

        "{\"sighting\":{\"occurred\":20200530,\"reported\":20200531,\"posted\":20200625,\"report\":{\"city\":\"New York Staten Island\",\"duration\":\"2 minutes\",\"shape\":[\"disk\"],\"state\":\"NY\",\"summary\":\"Round shaped object observed over Staten Island NYC, while sitting in my back yard. My daughter also observed this object . Bright White shaped object moving fast from East to West . Observed over Graniteville, Staten Island towards the Elizabeth NJ area and appears to be fast. We then lost view of it due to the clouds.\"}}}]";

// Convert string to Java Map

List<Map<String, Object>> sightingMap = new Gson().fromJson(sightings, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());

// Set an Aerospike bin with the bin name "sightings" and put the JSON document in as a map

Bin bin = new Bin(binName, Value.get(sightingMap));

// Create the write policy

WritePolicy writePolicy = new WritePolicy();

writePolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;

// Write the record to Aerospike

try {

    client.delete(null, key);

    client.put(writePolicy, key, bin);

    Record record = client.get(null, key);

    Object value = record.getValue(binName);

    System.out.printf("Create succeeded \nKey: %d \nRecord: %s\n", key.userKey.toLong(), new Gson().toJson(value));

}

catch (AerospikeException ae) {

    System.out.printf("Create failed\nError: %s\n", ae.getMessage());

}

// Create the update policy

WritePolicy updatePolicy = new WritePolicy();

updatePolicy.recordExistsAction = RecordExistsAction.UPDATE;

// Update the record written to Aerospike in the preceding step

try {

    // Update the sighting city in the first record in list of "sightings" from "Kirkland" to "Seattle"

    client.operate(updatePolicy, key,

            MapOperation.put(

                    new MapPolicy(MapOrder.KEY_VALUE_ORDERED, MapWriteMode.UPDATE),

                    binName, // Bin to be updated

                    Value.get("city"), // Key to be updated

                    Value.get("Seattle"), // Update value

                    CTX.listIndex(0), CTX.mapKey(Value.get("sighting")), CTX.mapKey(Value.get("report")))

    );

}

catch (AerospikeException ae) {

    System.out.printf("Update failed\nError: %s\n", ae.getMessage());

}

// Read updated record

Record record = client.get(null, key);

Object value = record.getValue(binName);

System.out.printf("Read succeeded \nKey: %d \nRecord: %s\n", key.userKey.toLong(), new Gson().toJson(value));

// Close the client

client.close();
```