X DevAPI User Guide

4.3.3 Collection.modify()

The modify(SearchConditionStr) function is for modifying documents in a collection, similar to an UPDATE statement for an SQL database. It takes a search condition string (SearchConditionStr) as a parameter to specify the documents that are to be modified—a detailed discussion on the SearchConditionStr can be found in Section 4.3.2, “Collection.find()”.

If one or more documents are matched by the search condition string, they are modified by any of these methods that are chained after the modify() method. They can be chained one after another and for multiple times:

Notes
  • The _id of a document cannot be modified or removed by the methods below.

  • For any methods below that take a DocPath expression as one of its arguments, the following rules apply:

    • Within the DocPath expression, any field names containing a space or a special character must be quoted; for example, set("name.'last name'", "Smith"), unset("name.'last%name'")

    • The DocPath expression cannot contain a wildcard token (either * or **).

    • The DocPath expression cannot be null or empty.

The following methods can be chained to the modification methods described above to configure the modification:

This is an example of using sort().limit() to limit modifications to the documents:

mysql-js> myColl.find("name like '%Doe'");
{
    "_id": "000062b0faf90000000000000001",
    "name": "Jane Doe",
    "favorNum": [
        2,
        3
    ]
}
{
    "_id": "000062b372f80000000000000001",
    "name": "Bob Doe",
    "favorNum": [
        1,
        2
    ]
}
{
    "_id": "000062b372f80000000000000002",
    "name": "Mark Doe",
    "favorNum": [
        7,
        8
    ]
}
{
    "_id": "000062b372f80000000000000003",
    "name": "John Doe",
    "favorNum": [
        0,
        4
    ]
}
mysql-js> myColl.modify("name like '%Doe'").unset("favorNum").sort("name asc").limit(2);
Query OK, 2 items affected (0.0082 sec)

Rows matched: 2  Changed: 2  Warnings: 0
mysql-js> myColl.find("name like '%Doe'").sort('name asc');
{
    "_id": "000062b372f80000000000000001",
    "name": "Bob Doe"
}
{
    "_id": "000062b0faf90000000000000001",
    "name": "Jane Doe"
}
{
    "_id": "000062b372f80000000000000003",
    "name": "John Doe",
    "favorNum": [
        0,
        4
    ]
}
{
    "_id": "000062b372f80000000000000002",
    "name": "Mark Doe",
    "favorNum": [
        7,
        8
    ]
}
4 documents in set (0.0068 sec)

Parameter binding using bind() is also supported. The execute() function triggers the actual execution of the modify() operation. The following example illustrates the use of modify():

MySQL Shell JavaScript Code

// Use the collection 'my_collection'
var myColl = db.getCollection('my_collection');

// Add a new document to the collection 
myColl.add({ name:"John Doe", DOB:"1970-01-01", Phone:1234567, Standing: "Good" }).execute();

// Patch the added document, adding, removing, and changing some fields 
myColl.modify("name = 'John Doe'").patch({ name: "Jane Doe", DOB: null, Phone: 9876543, favorNums: [1,2,3,4,5] }).execute();

//Modify fields with different methods
myColl.modify("name like :param").set("Standing", "Bad").bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("Phone").bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayInsert("favorNums[1]", 7).bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayAppend("favorNums", 99).bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("favorNums[2]").bind("param", "J%Doe").execute();

var doc = myColl.find('name like :param').limit(1).bind('param', 'J%Doe').execute();

print(doc.fetchOne());
/* The output looks like: 
{
    "Standing": "Bad", 
    "_id": "0000626718c10000000000000002", 
    "favorNums": [
        1, 
        7, 
        3, 
        4, 
        5, 
        99
    ], 
    "name": "Jane Doe"
} */


MySQL Shell Python Code

# Use the collection 'my_collection'
myColl = db.get_collection('my_collection')
# Add a new document to the collection 
myColl.add({ "name":"John Doe", "DOB":"1970-01-01", "Phone":1234567, "Standing": "Good" }).execute()

# Patch the added document, adding, removing, and changing some fields 
myColl.modify("name = 'John Doe'").patch({ "name": "Jane Doe", "DOB": None, "Phone": 9876543, "favorNums": [1,2,3,4,5] }).execute()

# Modify fields with different methods
myColl.modify("name like :param").set("Standing", "Bad").bind("param", "J%Doe").execute()
myColl.modify("name like :param").unset("Phone").bind("param", "J%Doe").execute()
myColl.modify("name like :param").array_insert("favorNums[1]", 7).bind("param", "J%Doe").execute()
myColl.modify("name like :param").array_append("favorNums", 99).bind("param", "J%Doe").execute()
myColl.modify("name like :param").unset("favorNums[2]").bind("param", "J%Doe").execute()

doc = myColl.find('name like :param').limit(1).bind('param', 'J%Doe').execute()

print(doc.fetch_one())

# The output looks like:
# {"Standing": "Bad", "_id": "0000626718c10000000000000005", "favorNums": [1, 7, 3, 4, 5, 99], "name": "Jane Doe"}

Node.js JavaScript Code

const mysqlx = require('@mysql/xdevapi');

mysqlx.getSession('mysqlx://localhost:33060')
    .then(session=> {
        const collection = session.getSchema('mySchema').getCollection('myCollection');
        // Add a new document to the collection 
        return collection.add({ name:"John Doe", DOB:"1970-01-01", Phone:1234567, Standing: "Good" })
          .execute()
          // Patch the added document, adding, removing, and changing some fields 
          .then(()=> {
            return collection.modify("name = 'John Doe'")
              .patch({ name: "Jane Doe", DOB: null, Phone: 9876543, favorNums: [1,2,3,4,5] })
              .execute();
          })
          // Modify fields with different methods
          .then(()=> {
            return collection.modify("name like :param")
              .set("Standing", "Bad")
              .bind("param", "J%Doe")
              .execute();
          })
          .then(()=> {
            return collection.modify("name like :param")
              .unset("Phone").bind("param", "J%Doe")
              .bind("param", "J%Doe")
              .execute();
          })
          .then(()=> {
            return collection.modify("name like :param")
              .arrayInsert("favorNums[1]", 7)
              .bind("param", "J%Doe")
              .execute();
          })
          .then(()=> {
            return collection.modify("name like :param")
              .arrayAppend("favorNums", 99)
              .bind("param", "J%Doe")
              .execute();
          })
          .then(()=> {
            return collection.modify("name like :param")
              .unset("favorNums[2]")
              .bind("param", "J%Doe")
              .execute();
          })
          .then(()=> {
            return collection.find('name like :param')
              .limit(1).bind('param', 'J%Doe')
              .execute();
          })
          .then(res => {
            console.log(res.fetchOne()); 
                     /* The output looks like: 
                       {
                        _id: '00006272fb890000000000000004',
                        name: 'Jane Doe',
                        Standing: 'Bad',
                        favorNums: [ 1, 7, 3, 4, 5, 99 ]
                       } */
           });
    });

C# Code

// Use the collection "my_collection"
var myColl = myDb.GetCollection("my_collection");

// Insert a document
myColl.Add(new { name = "John Doe", DOB = "1970-01-01", Phone = 1234567, Standing = "Good" }).Execute();

//Patch the added document, adding, removing, and changing some fields 
myColl.Modify("name = 'John Doe'")
  .Patch(new { name = "Jane Doe", DOB = (string)null, Phone = 9876543, favorNums = new[] { 1, 2, 3, 4, 5 } })
  .Execute();

//Modify fields with different methods
myColl.Modify("name like :param").Set("Standing", "Bad").Bind("param", "J%Doe").Execute();
myColl.Modify("name like :param").Unset("Phone").Bind("param", "J%Doe").Execute();
myColl.Modify("name like :param").ArrayInsert("favorNums[1]", 7).Bind("param", "J%Doe").Execute();
myColl.Modify("name like :param").ArrayAppend("favorNums", 99).Bind("param", "J%Doe").Execute();
myColl.Modify("name like :param").Unset("favorNums[2]").Bind("param", "J%Doe").Execute();

var docs = myColl.Find("name like :param").Limit(1).Bind("param", "J%Doe").Execute();
Console.WriteLine(docs.FetchOne());

/* The output looks like: 
   {
                  "_id": "00006274151a0000000000000004",
                  "name": "Jane Doe",
                  "Standing": "Bad",
                  "favorNums": [
                    1,
                    7,
                    3,
                    4,
                    5,
                    99
                  ]
                }
*/


Python Code

# Use the collection 'my_collection'
my_coll = my_schema.get_collection('my_collection')

# Add a new document to the collection 
my_coll.add({ "name":"John Doe", "DOB":"1970-01-01", "Phone":1234567, "Standing": "Good" }).execute()

# Patch the added document, adding, removing, and changing some fields 
my_coll.modify("name = 'John Doe'").patch({"name": "Jane Doe", "DOB": None, "Phone": 9876543, "favorNums": [1,2,3,4,5] }).execute()

# Modify fields with different methods
my_coll.modify("name like :param").set("Standing", "Bad").bind("param", "J%Doe").execute()
my_coll.modify("name like :param").unset("Phone").bind("param", "J%Doe").execute()
my_coll.modify("name like :param").array_insert("favorNums[1]", 7).bind("param", "J%Doe").execute()
my_coll.modify("name like :param").array_append("favorNums", 99).bind("param", "J%Doe").execute()
my_coll.modify("name like :param").unset("favorNums[2]").bind("param", "J%Doe").execute()

docs = my_coll.find('name like :param').limit(1).bind('param', 'J%Doe').execute()

print(docs.fetch_one())

# The output looks like:
#{"_id": "0000627ac9ac0000000000000007", "name": "Jane Doe", "Standing": "Bad", "favorNums": [1, 7, 3, 4, 5, 99]}

Java Code

// Use the collection 'my_collection'
Collection myColl = db.getCollection("my_collection");



// Add a new document to the collection 
myColl.add("{ \"name\":\"John Doe\", \"DOB\" : \"1970-01-01\", \"Phone\" : 1234567, \"Standing\" : \"Good\" }").execute();
   
// Patch the added document, adding, removing, and changing some fields 
myColl.modify("name = 'John Doe'").patch("{ \"name\": \"Jane Doe\", \"DOB\" : null, \"Phone\" : 9876543, \"favorNums\" : [1,2,3,4,5] }").execute();

//Modify fields with different methods
myColl.modify("name like :param").set("Standing", "Bad").bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("Phone").bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayInsert("favorNums[1]", 7).bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayAppend("favorNums", 99).bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("favorNums[2]").bind("param", "J%Doe").execute();

DocResult docs = myColl.find("name like : param").limit(1).bind("param", "J%Doe").execute();

while (docs.hasNext()) {
    DbDoc myDoc = docs.next();
    System.out.println(myDoc);
} 
    
//The output looks like:
//{"Standing":"Bad","_id":"0000627eadcb0000000000000001","favorNums":[1,7,3,4,5,99],"name":"Jane Doe"} 

C++ Code

Collection myColl = db.getCollection("my_collection");
          
// Add a new document to the collection 
myColl.add(R"({ "name":"John Doe", "DOB" : "1970-01-01", "Phone" : 1234567, "Standing" : "Good" })").execute();
   
// Patch the added document, adding, removing, and changing some fields 
myColl
  .modify("name = 'John Doe'")
  .patch(R"({
   "name": "Jane Doe", "DOB" : null, "Phone" : 9876543, "favorNums" : [1,2,3,4,5] 
   })")
  .execute();

//Modify fields with different methods
myColl.modify("name like :param").set("Standing", "Bad").bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("Phone").bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayInsert("favorNums[1]", 7).bind("param", "J%Doe").execute();
myColl.modify("name like :param").arrayAppend("favorNums", 99).bind("param", "J%Doe").execute();
myColl.modify("name like :param").unset("favorNums[2]").bind("param", "J%Doe").execute();

DocResult docs = myColl.find("name like :param").limit(1).bind("param", "J%Doe").execute();

DbDoc myDoc;
while ((myDoc = docs.fetchOne()))
    {
        cout << myDoc << endl;
    }
    
//The output looks like: 
// {"_id": "0000627ea0a80000000000000006", "name": "Jane Doe", "Standing": "Bad", "favorNums": [1, 7, 3, 4, 5, 99]}

See also CollectionModifyFunction for the syntax of add() in EBNF.