Update a JSON Field Value
In this step, we will learn how to update a JSON field value within a MySQL column using the JSON_SET
function. This function allows you to modify specific values in a JSON document based on a path.
First, let's connect to the MySQL server using the mysql
client. Open a terminal and execute the following command:
mysql -u root -p
You will be prompted for the root password. Since no password was set during installation, just press Enter
.
Next, select the jsondb
database we created in the previous step:
USE jsondb;
Now, let's use the JSON_SET
function to update the price of the laptop in the product_details
column. Suppose we want to increase the price to 1250.
UPDATE products
SET product_details = JSON_SET(product_details, '$.price', 1250)
WHERE product_name = 'Laptop';
In this UPDATE
statement, JSON_SET(product_details, '$.price', 1250)
modifies the product_details
JSON document by setting the value associated with the key "price" to 1250. The $.price
is a JSON path expression that specifies the path to the value to be updated.
To verify that the data has been updated correctly, let's query the table and check the price:
SELECT product_details->>'$.price' AS price FROM products WHERE product_name = 'Laptop';
You should see output similar to this:
+-------+
| price |
+-------+
| 1250 |
+-------+
1 row in set (0.00 sec)
This confirms that the price has been successfully updated to 1250.
Now, let's update the processor in the specs
object within the product_details
JSON document. Suppose we want to upgrade the processor to "Intel Core i9".
UPDATE products
SET product_details = JSON_SET(product_details, '$.specs.processor', 'Intel Core i9')
WHERE product_name = 'Laptop';
Here, $.specs.processor
specifies the path to the "processor" value within the "specs" object.
To verify the update, let's query the table again:
SELECT product_details->>'$.specs.processor' AS processor FROM products WHERE product_name = 'Laptop';
The output will be:
+-----------------+
| processor |
+-----------------+
| Intel Core i9 |
+-----------------+
1 row in set (0.00 sec)
This confirms that the processor has been updated to "Intel Core i9".
You can also add new fields to the JSON document using JSON_SET
. For example, let's add a new field called "color" with the value "Silver".
UPDATE products
SET product_details = JSON_SET(product_details, '$.color', 'Silver')
WHERE product_name = 'Laptop';
To verify the addition, let's query the table:
SELECT product_details->>'$.color' AS color FROM products WHERE product_name = 'Laptop';
The output will be:
+--------+
| color |
+--------+
| Silver |
+--------+
1 row in set (0.00 sec)
You can exit the MySQL client by typing exit
and pressing Enter
.
exit
In this step, you have learned how to use the JSON_SET
function to update existing JSON field values and add new fields to a JSON document in MySQL.