Thursday, May 7, 2020

Modify Multiple Documents in a MySQL Document Store Collection

The MySQL Document Store is an quick and easy to use NoSQL JSON Document Database that was designed to be easy to use.  But there is one thing that may not be obvious if you are working to modify multiple documents. 

So let us start with a very simple example collection of three documents.

>db.xyz.find()
{
    "a": 1,
    "_id": "00005eb2ba3c0000000000000004"
}
{
    "b": 2,
    "_id": "00005eb2ba3c0000000000000005"
}
{
    "c": 3,
    "_id": "00005eb2ba3c0000000000000006"
}
3 documents in set (0.0008 sec)

So we have three different documents and later determine we need to add the same key/value pair for all of them.

But the following will not work:

>db.xyz.modify().set("fizz","buzz")
Collection.modify: Invalid number of arguments, expected 1 but got 0 (ArgumentError)

The error message is trying to tell you that you need to a) specify one record (say where a = 1) to update just that one document or b) add 'true' to the modify() all of them.

>db.xyz.modify('true').set("fizz","buzz")
Query OK, 3 items affected (0.1389 sec)

>db.xyz.find()
{
    "a": 1,
    "_id": "00005eb2ba3c0000000000000004",
    "fizz": "buzz"
}
{
    "b": 2,
    "_id": "00005eb2ba3c0000000000000005",
    "fizz": "buzz"
}
{
    "c": 3,
    "_id": "00005eb2ba3c0000000000000006",
    "fizz": "buzz"
}
3 documents in set (0.0005 sec)

If you would prefer to see a video of this, please refer to my Github tutorials