1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Targetting elements of an array that are JSON data type?

Discussion in 'MySQL' started by gregnb, Apr 15, 2016.

  1. #1
    Hey everyone,

    I'm currently stuck at this problem which is say I have the following table created:

    CREATE TABLE employees(data JSON);

    INSERT INTO employees(data) VALUES
    ('{"name": "greg", "age": 25}'), ('{"name": "james", "age": 30}'),
    ('{"name": "jane", "age": 45}'), ('{"name": "alex", "age": 50}'),
    ('{"name": "bill", "age": 29}'), ('{"name": "tom", "age": 65}');


    UPDATE employees SET data = JSON_INSERT(data, '$.hours', JSON_ARRAY(8,10,12,16,11));

    Let's say I want to delete from that hours array inside the JSON data type where the hour = 8. How can I do this? The only way I know to remove an element from an array is knowing the exact position

    which I would do something like this:

    UPDATE employees SET data = JSON_REPLACE(data, '$.hours', JSON_REMOVE(JSON_EXTRACT(data,'$.hours'), '$[0]'))
    WHERE JSON_EXTRACT(data,'$.name') = 'greg';

    Is there anyway I could just search for this 8 without giving a position? I'm in the process of trying to learn it I've written a little article keeping notes on how I can use it at http://www.nowakowskig.com/blog/mysql-5-7-native-json-tutorial-nosql
     
    Last edited: Apr 16, 2016
    gregnb, Apr 15, 2016 IP