MySQL Shell对关系表进行操作

MySQL Shell不仅可以操作JSON文档,还可以操作关系表。

在MySQL中,每个关系表都与特定的存储引擎相关联。本节中的例子使用world_x数据库中的InnoDB表。

确认模式
要显示分配给模式变量的值,请输入db。

 MySQL  localhost:33060+  world_x  JS > db

如果schema值不是schema:world_x,则设置db变量如下:

mysql-js> \use world_x

显示所有表
要显示world_x数据库中的所有关系表,可以在schema对象上使用getTables()方法。

 MySQL  localhost:33060+  world_x  JS > db.getTables()
[
    ,
    ,
    ,
    
]

基本表操作
表的基本操作范围包括:
db.name.insert():insert()方法向指定的表中插入一条或多条记录。
db.name.select():select()方法返回指定表中的部分或全部记录。
db.name.update():update()方法更新指定表中的记录。
db.name.delete():delete()方法从指定的表中删除一条或多条记录。

向表中插入记录
可以结合values()方法使用insert()方法将记录插入到现有的关系表中。insert()方法接受单个列或表中的所有列作为参数。使用一个或 多个values()方法指定要插入的值。

插入完整记录
要插入完整的记录,向insert()方法传递表中的所有列。然后向values()方法传递表中的每一列的一个值。例如,要向world_x数据库中的 city表中添加一条新记录,插入下面的记录并按两次Enter键。

 MySQL  localhost:33060+  world_x  JS > db.city.insert("ID", "Name", "CountryCode", "District", "Info").values(null,  "Olympia", "USA", "Washington", '{"Population": 5000}')
Query OK, 1 item affected (0.0250 sec)

城市表有5列:ID、Name、CountryCode、District和Info。每个值必须与它表示的列的数据类型匹配。

插入部分记录
下面的示例将值插入city表的ID、Name和CountryCode列。

 MySQL  localhost:33060+  world_x  JS > db.city.insert("ID", "Name", "CountryCode").values(null, "Little Falls",  "USA").values(null, "Happy Valley", "USA")
Query OK, 2 items affected (0.0092 sec)

Records: 2  Duplicates: 0  Warnings: 0

使用insert()方法指定列时,值的数量必须与列的数量匹配。在前面的例子中,必须提供三个值来匹配指定的三列。

查询表记录
你可以使用select()方法从数据库的表中查询并返回记录。X DevAPI提供了与select()方法一起使用的其他方法,用于过滤和排序返回的记 录。

MySQL提供了以下运营商指定搜索条件:OR(| |),AND(& &),XOR IS,NOT,BETWEEN,IN,LIKE, !=, <>, >, >=, < , <=, &, |, <<, >>, +, -, *, /, ~, 和%。

查询所有记录
要查询已存在表中的所有记录,只需使用select()方法,而无需指定搜索条件。下面的示例从world_x数据库中的city表中选择所有记录。

将空的select()方法限制为交互式语句。始终在应用程序代码中使用显式的列名选择。

 MySQL  localhost:33060+  world_x  JS > db.city.select()
+------+--------------------------------+-------------+----------------------+-------------------------+
| ID   | Name                           | CountryCode | District             | Info                    |
+------+--------------------------------+-------------+----------------------+-------------------------+
|    1 | Kabul                          | AFG         | Kabol                | {"Population": 1780000} |
|    2 | Qandahar                       | AFG         | Qandahar             | {"Population": 237500}  |
|    3 | Herat                          | AFG         | Herat                | {"Population": 186800}  |
|    4 | Mazar-e-Sharif                 | AFG         | Balkh                | {"Population": 127800}  |
..................
| 4078 | Nablus                         | PSE         | Nablus               | {"Population": 100231}  |
| 4079 | Rafah                          | PSE         | Rafah                | {"Population": 92020}   |
| 4082 | Olympia                        | USA         | Washington           | {"Population": 5000}    |
| 4089 | Little Falls                   | USA         |                      | NULL                    |
| 4096 | Happy Valley                   | USA         |                      | NULL                    |
+------+--------------------------------+-------------+----------------------+-------------------------+
4082 rows in set (0.0024 sec)

过滤搜索
要发出一个返回一组表列的查询,可以使用select()方法,并在方括号中指定要返回的列。这个查询返回city表中的Name和CountryCode列。

 MySQL  localhost:33060+  world_x  JS > db.city.select(["Name", "CountryCode"])
+--------------------------------+-------------+
| Name                           | CountryCode |
+--------------------------------+-------------+
| Kabul                          | AFG         |
| Qandahar                       | AFG         |
| Herat                          | AFG         |
| Mazar-e-Sharif                 | AFG         |
.................
| Jabaliya                       | PSE         |
| Nablus                         | PSE         |
| Rafah                          | PSE         |
| Olympia                        | USA         |
| Little Falls                   | USA         |
| Happy Valley                   | USA         |
+--------------------------------+-------------+
4082 rows in set (0.0023 sec)

要查询返回符合特定搜索条件的行,可以使用where()方法来包含这些条件。例如,下面的示例返回以字母Z开头的城市的名称和国家代码。

 MySQL  localhost:33060+  world_x  JS > db.city.select(["Name", "CountryCode"]).where("Name like 'Z%'")
+-----------------+-------------+
| Name            | CountryCode |
+-----------------+-------------+
| Zaanstad        | NLD         |
| Zoetermeer      | NLD         |
| Zwolle          | NLD         |
| Zenica          | BIH         |
| Zagazig         | EGY         |
| Zaragoza        | ESP         |
| Zamboanga       | PHL         |
| Zahedan         | IRN         |
| Zanjan          | IRN         |
| Zabol           | IRN         |
| Zama            | JPN         |
| Zhezqazghan     | KAZ         |
| Zhengzhou       | CHN         |
| Zibo            | CHN         |
| Zhangjiakou     | CHN         |
| Zhuzhou         | CHN         |
| Zhangjiang      | CHN         |
| Zigong          | CHN         |
| Zaozhuang       | CHN         |
| Zhenjiang       | CHN         |
| Zhongshan       | CHN         |
| Zunyi           | CHN         |
| Zhaoqing        | CHN         |
| Zhangzhou       | CHN         |
| Zhaodong        | CHN         |
| Zhuhai          | CHN         |
| Zaoyang         | CHN         |
| Zhoushan        | CHN         |
| Zhoukou         | CHN         |
| Zalantun        | CHN         |
| Zhumadian       | CHN         |
| Zixing          | CHN         |
| Zhucheng        | CHN         |
| Zhangjiagang    | CHN         |
| Zagreb          | HRV         |
| Zapopan         | MEX         |
| Zamora          | MEX         |
| Zitácuaro       | MEX         |
| Zacatecas       | MEX         |
| Zinacantepec    | MEX         |
| Zumpango        | MEX         |
| Zinder          | NER         |
| Zaria           | NGA         |
| Zabrze          | POL         |
| Zielona Góra    | POL         |
| Zwickau         | DEU         |
| Ziguinchor      | SEN         |
| Zürich          | CHE         |
| Zanzibar        | TZA         |
| Zonguldak       | TUR         |
| Zaporizzja      | UKR         |
| Zytomyr         | UKR         |
| Zelenograd      | RUS         |
| Zlatoust        | RUS         |
| Zelenodolsk     | RUS         |
| Zeleznodoroznyi | RUS         |
| Zeleznogorsk    | RUS         |
| Zukovski        | RUS         |
| Zeleznogorsk    | RUS         |
+-----------------+-------------+
59 rows in set (0.0049 sec)

可以使用bind()方法将值与搜索条件分开。例如,不使用“Name = ‘Z%’ ”作为条件,而是使用冒号和以字母开头的名称组成的命名占位符, 例如Name。然后在bind()方法中包含占位符和值,如下所示:

 MySQL  localhost:33060+  world_x  JS > db.city.select(["Name", "CountryCode"]).where("Name like :name").bind("name", "Z%")
+-----------------+-------------+
| Name            | CountryCode |
+-----------------+-------------+
| Zaanstad        | NLD         |
| Zoetermeer      | NLD         |
| Zwolle          | NLD         |
| Zenica          | BIH         |
| Zagazig         | EGY         |
| Zaragoza        | ESP         |
| Zamboanga       | PHL         |
| Zahedan         | IRN         |
| Zanjan          | IRN         |
| Zabol           | IRN         |
| Zama            | JPN         |
| Zhezqazghan     | KAZ         |
| Zhengzhou       | CHN         |
| Zibo            | CHN         |
| Zhangjiakou     | CHN         |
| Zhuzhou         | CHN         |
| Zhangjiang      | CHN         |
| Zigong          | CHN         |
| Zaozhuang       | CHN         |
| Zhenjiang       | CHN         |
| Zhongshan       | CHN         |
| Zunyi           | CHN         |
| Zhaoqing        | CHN         |
| Zhangzhou       | CHN         |
| Zhaodong        | CHN         |
| Zhuhai          | CHN         |
| Zaoyang         | CHN         |
| Zhoushan        | CHN         |
| Zhoukou         | CHN         |
| Zalantun        | CHN         |
| Zhumadian       | CHN         |
| Zixing          | CHN         |
| Zhucheng        | CHN         |
| Zhangjiagang    | CHN         |
| Zagreb          | HRV         |
| Zapopan         | MEX         |
| Zamora          | MEX         |
| Zitácuaro       | MEX         |
| Zacatecas       | MEX         |
| Zinacantepec    | MEX         |
| Zumpango        | MEX         |
| Zinder          | NER         |
| Zaria           | NGA         |
| Zabrze          | POL         |
| Zielona Góra    | POL         |
| Zwickau         | DEU         |
| Ziguinchor      | SEN         |
| Zürich          | CHE         |
| Zanzibar        | TZA         |
| Zonguldak       | TUR         |
| Zaporizzja      | UKR         |
| Zytomyr         | UKR         |
| Zelenograd      | RUS         |
| Zlatoust        | RUS         |
| Zelenodolsk     | RUS         |
| Zeleznodoroznyi | RUS         |
| Zeleznogorsk    | RUS         |
| Zukovski        | RUS         |
| Zeleznogorsk    | RUS         |
+-----------------+-------------+
59 rows in set (0.0040 sec)

要使用AND操作符进行查询,在where()方法的搜索条件之间添加操作符。

 MySQL  localhost:33060+  world_x  JS > db.city.select(["Name", "CountryCode"]).where("Name like 'Z%' and CountryCode =  'CHN'")
+--------------+-------------+
| Name         | CountryCode |
+--------------+-------------+
| Zhengzhou    | CHN         |
| Zibo         | CHN         |
| Zhangjiakou  | CHN         |
| Zhuzhou      | CHN         |
| Zhangjiang   | CHN         |
| Zigong       | CHN         |
| Zaozhuang    | CHN         |
| Zhenjiang    | CHN         |
| Zhongshan    | CHN         |
| Zunyi        | CHN         |
| Zhaoqing     | CHN         |
| Zhangzhou    | CHN         |
| Zhaodong     | CHN         |
| Zhuhai       | CHN         |
| Zaoyang      | CHN         |
| Zhoushan     | CHN         |
| Zhoukou      | CHN         |
| Zalantun     | CHN         |
| Zhumadian    | CHN         |
| Zixing       | CHN         |
| Zhucheng     | CHN         |
| Zhangjiagang | CHN         |
+--------------+-------------+
22 rows in set (0.0051 sec)

要指定多个条件运算符,可以将搜索条件放在括号中以更改运算符的优先级。下面的例子演示了AND和OR操作符的位置。

 MySQL  localhost:33060+  world_x  JS > db.city.select(["Name", "CountryCode"]).where("Name like 'Z%' and (CountryCode = 'CHN'  or CountryCode = 'RUS')")
+-----------------+-------------+
| Name            | CountryCode |
+-----------------+-------------+
| Zhengzhou       | CHN         |
| Zibo            | CHN         |
| Zhangjiakou     | CHN         |
| Zhuzhou         | CHN         |
| Zhangjiang      | CHN         |
| Zigong          | CHN         |
| Zaozhuang       | CHN         |
| Zhenjiang       | CHN         |
| Zhongshan       | CHN         |
| Zunyi           | CHN         |
| Zhaoqing        | CHN         |
| Zhangzhou       | CHN         |
| Zhaodong        | CHN         |
| Zhuhai          | CHN         |
| Zaoyang         | CHN         |
| Zhoushan        | CHN         |
| Zhoukou         | CHN         |
| Zalantun        | CHN         |
| Zhumadian       | CHN         |
| Zixing          | CHN         |
| Zhucheng        | CHN         |
| Zhangjiagang    | CHN         |
| Zelenograd      | RUS         |
| Zlatoust        | RUS         |
| Zelenodolsk     | RUS         |
| Zeleznodoroznyi | RUS         |
| Zeleznogorsk    | RUS         |
| Zukovski        | RUS         |
| Zeleznogorsk    | RUS         |
+-----------------+-------------+
29 rows in set (0.0042 sec)

可以使用limit()、orderBy()和offSet()方法来管理select()方法返回的记录的数量和顺序。

要指定结果集中包含的记录数,可以在limit()方法后面添加一个值给select()方法。例如,下面的查询返回country表中的前5条记录。

 MySQL  localhost:33060+  world_x  JS > db.country.select(["Code", "Name"]).limit(5)
+------+-------------+
| Code | Name        |
+------+-------------+
| ABW  | Aruba       |
| AFG  | Afghanistan |
| AGO  | Angola      |
| AIA  | Anguilla    |
| ALB  | Albania     |
+------+-------------+
5 rows in set (0.0013 sec)

要指定结果的顺序,可以在select()方法后面添加orderBy()方法。向orderBy()方法传递一个列表,其中包含一个或多个用于排序的列, 还可以根据需要传递降序(desc)或升序(asc)属性。升序是默认的排序类型。

例如,下面的查询按Name列对所有记录进行排序,然后按降序返回前三条记录。

 MySQL  localhost:33060+  world_x  JS > db.country.select(["Code", "Name"]).orderBy(["Name desc"]).limit(3)
+------+------------+
| Code | Name       |
+------+------------+
| ZWE  | Zimbabwe   |
| ZMB  | Zambia     |
| YUG  | Yugoslavia |
+------+------------+
3 rows in set (0.0016 sec)

默认情况下,limit()方法从表中的第一条记录开始。可以使用offset()方法修改起始记录。例如,要忽略第一条记录并返回符合条件的后 三条记录,可以向offset()方法传递一个值1。

 MySQL  localhost:33060+  world_x  JS > db.country.select(["Code", "Name"]).orderBy(["Name desc"]).limit(3).offset(1)
+------+------------+
| Code | Name       |
+------+------------+
| ZMB  | Zambia     |
| YUG  | Yugoslavia |
| YEM  | Yemen      |
+------+------------+
3 rows in set (0.0015 sec)

更新表记录
可以使用update()方法修改表中的一条或多条记录。update()方法的工作原理是过滤一个查询,只包含需要更新的记录,然后对这些记录应 用指定的操作。

要替换city表中的城市名,向set()方法传递新的城市名。然后,向where()方法传递要定位和替换的城市名。下面的例子将北京这个城市替 换为北京。

 MySQL  localhost:33060+  world_x  JS > db.city.update().set("Name", "Beijing").where("Name = 'Peking'")
Query OK, 1 item affected (0.0299 sec)

Rows matched: 1  Changed: 1  Warnings: 0

使用select()方法验证修改。

 MySQL  localhost:33060+  world_x  JS > db.city.select(["ID", "Name", "CountryCode", "District", "Info"]).where("Name =  'Beijing'")
+------+---------+-------------+----------+-------------------------+
| ID   | Name    | CountryCode | District | Info                    |
+------+---------+-------------+----------+-------------------------+
| 1891 | Beijing | CHN         | Peking   | {"Population": 7472000} |
+------+---------+-------------+----------+-------------------------+
1 row in set (0.0072 sec)

删除表记录
你可以使用delete()方法从数据库的一张表中删除部分或全部记录。X DevAPI提供了额外的方法与delete()方法一起使用,用于过滤和排序 要删除的记录。

使用条件删除记录
下面的例子将搜索条件传递给delete()方法。所有符合条件的记录都将从city表中删除。在这个例子中,只有一条记录符合条件。

 MySQL  localhost:33060+  world_x  JS > db.city.delete().where("Name = 'Olympia'")
Query OK, 1 item affected (0.0130 sec)

删除第一条记录
要删除city表中的第一条记录,可以使用limit()方法将值设为1。

 MySQL  localhost:33060+  world_x  JS > db.city.delete().limit(1)
Query OK, 1 item affected (0.0060 sec)

删除表中的所有记录
可以删除表中的所有记录。为此,可以使用delete()方法,但不指定搜索条件。在没有指定搜索条件的情况下删除记录时要小心。该操作将从 表中删除所有记录。

MySQL 文档与集合

文档和集合
在MySQL中,集合包含JSON文档,你可以添加、查找、更新和删除这些文档。集合是模式中的容器,可以创建、列出和删除。

文档
在MySQL中,文档表示为JSON对象。在内部,它们以高效的二进制格式存储,支持快速查找和更新。
.JavaScript的简单文档格式:

{field1: "value", field2 : 10, "field 3": null}

文档数组由一组用逗号分隔、用[和]字符包裹的文档组成。

[{Name: "Aruba", _id: "ABW"}, {Name: "Angola", _id: "AGO"}]

MySQL支持JSON文档中的以下JavaScript值类型:
.数字(整数和浮点数)
.字符串
.布尔值(false和true)
.null
.包含更多JSON值的数组
.具有更多JSON值的嵌套(或嵌入)对象

集合
集合是用于共享目的的文档的容器,并且可能共享一个或多个索引。每个集合都有唯一的名称,并且存在于单一的模式中。
术语模式等同于数据库,意味着一组数据库对象(与之相对的是用于强制数据的结构和约束的关系模式)。模式并不强制集合中的文档保持一致性。基本对象包括:
.db:
db是一个全局变量,该变量分配给您在命令行上指定的当前活动模式。你可以在MySQL Shell中输入db来打印对象的描述,在本例中就是它所代表的模式的名称。

.db.getCollections():db.getCollections()保存了模式中的集合列表。使用列表获取集合对象的引用,迭代它们,等等。

集合作用域的基本操作包括:
.db.name.add():add()方法将一个文档或一个文档列表插入到指定的集合中。
.db.name.find():find()方法返回指定集合中的部分或全部文档。
.db.name.modify():方法modify()更新指定集合中的文档。
.db.name.remove():remove()方法从指定集合中删除一个文档或一个文档列表。

创建、显示和删除集合
在MySQL Shell中,你可以创建新的集合,获取模式中已存在集合的列表,或者从模式中删除已存在的集合。集合名称区分大小写,每个集合名称必须唯一。
确认模式
要显示分配给模式变量的值,请输入db。

 MySQL  localhost:33060+  world_x  JS > db

 MySQL  localhost:33060+  world_x  JS > 

如果schema值不是schema:world_x,则设置db变量如下:

 MySQL  localhost:33060+  JS > db
 MySQL  localhost:33060+  JS > \use world_x
Default schema `world_x` accessible through db.
 MySQL  localhost:33060+  world_x  JS > db

 MySQL  localhost:33060+  world_x  JS > 

创建一个集合
要在现有模式中创建新集合,可以使用createCollection()方法。下面的示例在world_x数据库中创建一个名为flags的集合。该方法返回一个集合对象。

 MySQL  localhost:33060+  world_x  JS > db.createCollection("flags")

 MySQL  localhost:33060+  world_x  JS > 

显示集合
要显示world_x数据库中的所有集合,可以在schema对象上使用getCollections()方法。服务器返回的集合出现在括号中。

 MySQL  localhost:33060+  world_x  JS > db.getCollections()
[
    
]
 MySQL  localhost:33060+  world_x  JS > 

删除集合
要从数据库中删除已有的集合,可以在session对象上调用dropCollection()方法。例如,要从world_x数据库中删除flags集合,输入:

 MySQL  localhost:33060+  world_x  JS > db.dropCollection("flags")
 MySQL  localhost:33060+  world_x  JS > db.getCollections()
[]

添加文档
使用MySQL Shell,可以使用add()方法将一个文档或一个列表文档插入到现有的集合中。本节中的所有示例都使用flags集合。
确认模式
要显示分配给模式变量的值,请输入db。

 MySQL  localhost:33060+  world_x  JS > db

如果schema值不是schema:world_x,则设置db变量如下:

 MySQL  localhost:33060+  JS > db
 MySQL  localhost:33060+  JS > \use world_x
Default schema `world_x` accessible through db.

添加文档
将下面的文档插入flags集合。按两次Enter键插入文档。

  MySQL  localhost:33060+  world_x  JS > db.createCollection("flags")


mysql> desc flags
    -> ;
+-------+-------------+------+-----+---------+------------------+
| Field | Type        | Null | Key | Default | Extra            |
+-------+-------------+------+-----+---------+------------------+
| doc   | json        | YES  |     | NULL    |                  |
| _id   | varchar(32) | NO   | PRI | NULL    | STORED GENERATED |
+-------+-------------+------+-----+---------+------------------+
2 rows in set (0.00 sec)



 MySQL  localhost:33060+  world_x  JS > db.getCollections()
[
    
]
 MySQL  localhost:33060+  world_x  JS >  db.flags.add(
                                     ->  {
                                     ->   GNP: .6,
                                     ->   IndepYear: 1967,
                                     ->   Name: "Sealand",
                                     ->   _id: "SEA",
                                     ->   demographics: {
                                     ->       LifeExpectancy: 79,
                                     ->       Population: 27
                                     ->   },
                                     ->   geography: {
                                     ->       Continent: "Europe",
                                     ->       Region: "British Islands",
                                     ->       SurfaceArea: 193
                                     ->   },
                                     ->   government: {
                                     ->       GovernmentForm: "Monarchy",
                                     ->       HeadOfState: "Michael Bates"
                                     ->   }
                                     ->  }
                                     -> )
                                     -> 
Query OK, 1 item affected (0.0073 sec)
 MySQL  localhost:33060+  world_x  JS > 

该方法返回操作的状态。

每个文档都需要一个名为_id的标识符字段。_id字段的值必须在同一个集合中的所有文档中唯一。如果传递给add()方法的文档不包含_id字段
,MySQL Shell会自动在文档中插入一个字段,并设置该字段的值为生成的UUID (universal unique identifier,通用唯一标识符)。

查找文档
可以使用find()方法从数据库中的集合中查询并返回文档。MySQL Shell为find()方法提供了额外的方法来过滤和排序返回的文档。
MySQL提供了以下运营商指定搜索条件:OR (||), AND (&&), XOR, IS, NOT,BETWEEN, IN, LIKE, !=, <>, >, >=, < , <=, &, |, <<, >>, +, -, *, /, ~, 和 %.

查找集合中的所有文档
要返回集合中的所有文档,可以使用find()方法,但不指定搜索条件。例如,下面的操作返回flags集合中的所有文档。

Query OK, 1 item affected (0.0154 sec)
 MySQL  localhost:33060+  world_x  JS > db.flags.find();
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
{
    "GNP": 0.6,
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
2 documents in set (0.0009 sec)

该方法生成的结果除了包含集合中的所有文档外,还包含操作信息。
一个空集合(没有匹配的文档)返回以下信息:

Empty set (0.00 sec)

过滤搜索
你可以在find()方法中包含搜索条件。组成搜索条件的表达式的语法与传统MySQL相同。所有表达式必须用引号括起来。
本节中的所有示例都使用world_x数据库中的flags集合。为简洁起见,有些示例不显示输出。
一个简单的搜索条件由_id字段和文档的唯一标识符组成。下面的例子返回一个与标识符字符串匹配的文档:

 MySQL  localhost:33060+  world_x  JS > db.flags.find("_id = 'SEA'")
{
    "GNP": 0.6,
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
1 document in set (0.0023 sec)
 MySQL  localhost:33060+  world_x  JS > 

下面的示例搜索GNP高于3000亿美元的所有国家。国家信息收集以百万为单位衡量国民生产总值。

 MySQL  localhost:33060+  world_x  JS > db.flags.find("GNP > 300000");
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
1 document in set (0.0012 sec)

下面查询中的Population字段嵌入到人口统计对象中。要访问嵌入式字段,使用人口统计数据和人口之间的句号来识别关系。文档名和字段名区分大小写。

 MySQL  localhost:33060+  world_x  JS > db.flags.find("GNP > 300000 and demographics.Population <100000000")
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
1 document in set (0.0012 sec)

可以使用bind()方法将值与搜索条件分开。例如,与其指定硬编码的国家名作为条件,不如用冒号和以字母开头的名称(如country)组成的命名占位符。然后在bind()方法中包含占位符和值,如下所示:

 MySQL  localhost:33060+  world_x  JS > db.flags.find("Name = :country").bind("country", "Sealand")
{
    "GNP": 0.6,
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
1 document in set (0.0059 sec)

在程序中,绑定使您能够在表达式中指定占位符,这些占位符在执行之前被填充值,并且可以根据需要从自动转义中获益。始终使用绑定来清理输入。使用字符串连接避免在查询中引入值,这会产生无效的输入,在某些情况下,可能会导致安全问题。
可以返回文档的特定字段,而不是返回所有字段。下面的示例返回flags集合中匹配搜索条件的所有文档的GNP和Name字段。
使用fields()方法传递要返回的字段列表

 MySQL  localhost:33060+  world_x  JS > db.flags.find("GNP > 300000").fields(["GNP","Name"])
{
    "GNP": 351182,
    "Name": "Australia"
}
1 document in set (0.0017 sec)

此外,您可以使用描述要返回的文档的表达式来更改返回的文档——添加、重命名、嵌套甚至计算新的字段值。例如,使用下面的表达式更改字段的名称,使其仅返回两个文档。

 MySQL  localhost:33060+  world_x  JS > db.flags.find().fields(mysqlx.expr('{"Name": upper(Name), "GNPPerCapita": 

GNP*1000000/demographics.Population}')).limit(2)
{
    "Name": "AUSTRALIA",
    "GNPPerCapita": 18594.832150799535
}
{
    "Name": "SEALAND",
    "GNPPerCapita": 22222.222222222223
}
2 documents in set (0.0019 sec)

限制、排序和跳过结果
可以应用limit()、sort()和skip()方法来管理find()方法返回的文档数量和顺序。
要指定结果集中包含的文档数量,请将带有值的limit()方法附加到find()方法。下面的查询返回flags集合中的第一个文档。

 MySQL  localhost:33060+  world_x  JS > db.flags.find().limit(1)
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
1 document in set (0.0031 sec)

要指定结果的顺序,请将sort()方法附加到find()方法后。将一个或多个要排序的字段的列表传递给sort()方法,并根据需要可选地传递降序(desc)或升序(asc)属性。升序是默认的顺序类型。
例如,下面的查询按IndepYear字段对所有文档进行排序,然后按降序返回前2个文档。

 MySQL  localhost:33060+  world_x  JS > db.flags.find().sort(["IndepYear desc"]).limit(2)
{
    "GNP": 0.6,
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
2 documents in set (0.0032 sec)

默认情况下,limit()方法从集合中的第一个文档开始。您可以使用skip()方法来更改起始文档。例如,要忽略第一个文档并返回后面1个匹配条件的文档,可以将值1传递给skip()方法。

 MySQL  localhost:33060+  world_x  JS > db.flags.find().sort(["IndepYear desc"]).limit(1).skip(1)
{
    "GNP": 351182,
    "_id": "AUS",
    "Name": "Australia",
    "IndepYear": 1901,
    "geography": {
        "Region": "Australia and New Zealand",
        "Continent": "Oceania",
        "SurfaceArea": 7741220
    },
    "government": {
        "HeadOfState": "Elisabeth II",
        "GovernmentForm": "Constitutional Monarchy, Federation"
    },
    "demographics": {
        "Population": 18886000,
        "LifeExpectancy": 79.80000305175781
    }
}
1 document in set (0.0015 sec)

修改文档
可以使用modify()方法更新集合中的一个或多个文档。X DevAPI提供了与modify()方法一起使用的附加方法:
.设置和取消设置文档中的字段。
.追加、插入和删除数组。
.对要修改的文档进行绑定、限制和排序。

设置和取消设置文档中的字段
modify()方法的工作原理是过滤一个集合,使其只包含要修改的文档,然后将您指定的操作应用于这些文档。
在下面的示例中,modify()方法使用搜索条件来标识要更改的文档,然后set()方法替换嵌套的人口统计对象中的两个值。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("_id = 'SEA'").set("demographics", {LifeExpectancy: 78, Population: 

28})
Query OK, 1 item affected (0.0333 sec)

Rows matched: 1  Changed: 1  Warnings: 0

在修改文档之后,使用find()方法来验证更改。

 MySQL  localhost:33060+  world_x  JS > db.flags.find("_id = 'SEA'")
{
    "GNP": 0.6,
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 28,
        "LifeExpectancy": 78
    }
}
1 document in set (0.0010 sec)

要从文档中删除内容,请使用modify()和unset()方法。例如,下面的查询从匹配搜索条件的文档中删除GNP。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("Name = 'Sealand'").unset("GNP")
Query OK, 1 item affected (0.0072 sec)

Rows matched: 1  Changed: 1  Warnings: 0

使用find()方法验证更改。

 MySQL  localhost:33060+  world_x  JS > db.flags.find("Name = 'Sealand'")
{
    "_id": "SEA",
    "Name": "Sealand",
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 28,
        "LifeExpectancy": 78
    }
}
1 document in set (0.0010 sec)

追加、插入和删除数组
使用arrayAppend()、arrayInsert()或arrayDelete()方法向数组字段添加元素,或在数组中插入或删除元素。下面的示例修改了flags集合,以启用对国际机场的跟踪。
第一个示例使用modify()和set()方法在所有文档中创建一个新的Airports字段。
在不指定搜索条件的情况下修改文档时要小心。此操作将修改集合中的所有文档。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("true").set("Airports", [])
Query OK, 3 items affected (0.0071 sec)

Rows matched: 3  Changed: 3  Warnings: 0

添加了Airports字段后,下一个示例将使用arrayAppend()方法向其中一个文档添加一个新机场。美元。下面示例中的Airports表示当前文档的Airports字段。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("Name = 'France'").arrayAppend("$.Airports", "ORY")
Query OK, 1 item affected (0.0069 sec)

Rows matched: 1  Changed: 1  Warnings: 0

使用db.flags.find”Name = ‘France'”)查看更改。

 MySQL  localhost:33060+  world_x  JS > db.flags.find("Name = 'France'")
{
    "GNP": 5000000,
    "_id": "FRA",
    "Name": "France",
    "Airports": [
        "ORY"
    ],
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
1 document in set (0.0013 sec)

要在数组的不同位置插入元素,可以使用arrayInsert()方法在路径表达式中指定要插入的索引。在这个例子中,索引是0,即数组的第一个元素。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("Name = 'France'").arrayInsert("$.Airports[0]", "CDG")
Query OK, 1 item affected (0.0078 sec)

Rows matched: 1  Changed: 1  Warnings: 0
 MySQL  localhost:33060+  world_x  JS > db.flags.find("Name = 'France'")
{
    "GNP": 5000000,
    "_id": "FRA",
    "Name": "France",
    "Airports": [
        "CDG",
        "ORY"
    ],
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
1 document in set (0.0010 sec)

要从数组中删除一个元素,必须将要删除的元素的索引传递给arrayDelete()方法。

 MySQL  localhost:33060+  world_x  JS > db.flags.modify("Name = 'France'").arrayDelete("$.Airports[1]")
Query OK, 1 item affected (0.0057 sec)

Rows matched: 1  Changed: 1  Warnings: 0
 MySQL  localhost:33060+  world_x  JS > db.flags.find("Name = 'France'")
{
    "GNP": 5000000,
    "_id": "FRA",
    "Name": "France",
    "Airports": [
        "CDG"
    ],
    "IndepYear": 1967,
    "geography": {
        "Region": "British Islands",
        "Continent": "Europe",
        "SurfaceArea": 193
    },
    "government": {
        "HeadOfState": "Michael Bates",
        "GovernmentForm": "Monarchy"
    },
    "demographics": {
        "Population": 27,
        "LifeExpectancy": 79
    }
}
1 document in set (0.0009 sec)

删除文档
可以使用remove()方法从数据库集合中删除部分或全部文档。X DevAPI为remove()方法提供了额外的方法,用于过滤和排序要删除的文档。

使用条件删除文档
下面的例子向remove()方法传递了一个搜索条件。所有符合条件的文档都将从countryinfo集合中删除。在这个例子中,有一个文档符合条件。

 MySQL  localhost:33060+  world_x  JS > db.flags.remove("_id = 'SEA'")
Query OK, 1 item affected (0.0159 sec)

删除第一个文档
要删除flags集合中的第一个文档,可使用limit()方法,将值设为1。

 MySQL  localhost:33060+  world_x  JS > db.flags.remove("true").limit(1)
Query OK, 1 item affected (0.0058 sec)

按顺序删除最后一个文档
下面的示例按国家名删除countryinfo集合中的最后一个文档。

 MySQL  localhost:33060+  world_x  JS > db.flags.remove("true").sort(["Name desc"]).limit(1)
Query OK, 1 item affected (0.02 sec)

删除集合中的所有文档
可以删除集合中的所有文档。为此,可以使用remove(”true”)方法,但不指定任何搜索条件。

 MySQL  localhost:33060+  world_x  JS > db.flags.remove("true");
Query OK, 1 item affected (0.0063 sec)

MySQL Shell

MySQL Shell是MySQL服务器的统一脚本接口。它支持JavaScript和Python脚本。JavaScript是默认的处理模式。在大多数情况下,你需要一个账户来连接到本地的MySQL服务器实例。

启动MySQL Shell
安装并启动MySQL server后,将MySQL Shell连接到server实例。默认情况下,MySQL Shell使用X协议连接。

在运行server实例的系统上,打开一个终端窗口,并使用以下命令启动MySQL Shell:

mysqlsh name@localhost/world_x
Creating a Session to 'root@localhost/world_x'
Enter password: ****

您可能需要指定适当的路径。

另外:
.name表示MySQL帐户的用户名。
.MySQL Shell提示您输入密码。
.这个会话的默认模式是world_x数据库。

mysql-js>提示符表明此会话的活动语言是JavaScript。

[root@localhost ~]# mysqlsh root@localhost/world_x
Please provide the password for 'root@localhost': ******
Save password for 'root@localhost'? [Y]es/[N]o/Ne[v]er (default No): N
MySQL Shell 8.0.41

Copyright (c) 2016, 2025, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
Creating a session to 'root@localhost/world_x'
Fetching schema names for auto-completion... Press ^C to stop.
Your MySQL connection id is 61 (X protocol)
Server version: 5.7.26-log Source distribution
Default schema `world_x` accessible through db.
 MySQL  localhost:33060+  world_x  JS > 

当不带host参数运行mysqlsh时,MySQL Shell会尝试连接运行在localhost接口上的33060端口上的服务器实例。

MySQL Shell支持如下的输入行编辑:
.左箭头键和右箭头键在当前输入行内水平移动。
.向上箭头键和向下箭头键在先前输入的行集合中向上和向下移动。
.退格键删除光标之前的字符,输入新的字符将在光标位置输入。
.Enter输入当前输入行。

获取MySQL Shell的帮助
在命令解释器的提示符下输入mysqlsh –help以获取命令行选项列表。

[root@localhost ~]# mysqlsh --help
MySQL Shell 8.0.41

Copyright (c) 2016, 2025, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Usage: mysqlsh [OPTIONS] [URI]
       mysqlsh [OPTIONS] [URI] -f  [

在MySQL Shell提示符下输入\help,查看可用命令及其描述。

 MySQL  localhost:33060+  world_x  JS > \help
The Shell Help is organized in categories and topics. To get help for a
specific category or topic use: \? 

The  argument should be the name of a category or a topic.

The pattern is a filter to identify topics for which help is required, it can
use the following wildcards:

- ? matches any single character.
- * matches any character sequence.

The following are the main help categories:

 - AdminAPI       The AdminAPI is an API that enables configuring and managing
                  InnoDB Clusters, ReplicaSets, ClusterSets, among other
                  things.
 - Shell Commands Provides details about the available built-in shell commands.
 - ShellAPI       Contains information about the shell and util global objects
                  as well as the mysql module that enables executing SQL on
                  MySQL Servers.
 - SQL Syntax     Entry point to retrieve syntax help on SQL statements.
 - X DevAPI       Details the mysqlx module as well as the capabilities of the
                  X DevAPI which enable working with MySQL as a Document Store

The available topics include:

- The dba global object and the classes available at the AdminAPI.
- The mysqlx module and the classes available at the X DevAPI.
- The mysql module and the global objects and classes available at the
  ShellAPI.
- The functions and properties of the classes exposed by the APIs.
- The available shell commands.
- Any word that is part of an SQL statement.
- Command Line - invoking built-in shell functions without entering interactive
  mode.

SHELL COMMANDS

The shell commands allow executing specific operations including updating the
shell configuration.

The following shell commands are available:

 - \                   Start multi-line input when in SQL mode.
 - \connect    (\c)    Connects the shell to a MySQL server and assigns the
                       global session.
 - \disconnect         Disconnects the global session.
 - \edit       (\e)    Launch a system editor to edit a command to be executed.
 - \exit               Exits the MySQL Shell, same as \quit.
 - \help       (\?,\h) Prints help information about a specific topic.
 - \history            View and edit command line history.
 - \js                 Switches to JavaScript processing mode.
 - \nopager            Disables the current pager.
 - \nowarnings (\w)    Don't show warnings after every statement.
 - \option             Allows working with the available shell options.
 - \pager      (\P)    Sets the current pager.
 - \py                 Switches to Python processing mode.
 - \quit       (\q)    Exits the MySQL Shell.
 - \reconnect          Reconnects the global session.
 - \rehash             Refresh the autocompletion cache.
 - \show               Executes the given report with provided options and
                       arguments.
 - \source     (\.)    Loads and executes a script from a file.
 - \sql                Executes SQL statement or switches to SQL processing
                       mode when no statement is given.
 - \status     (\s)    Print information about the current global session.
 - \system     (\!)    Execute a system shell command.
 - \use        (\u)    Sets the active schema.
 - \warnings   (\W)    Show warnings after every statement.
 - \watch              Executes the given report with provided options and
                       arguments in a loop.

GLOBAL OBJECTS

The following modules and objects are ready for use when the shell starts:

 - db      Used to work with database schema objects.
 - dba     Used for InnoDB Cluster, ReplicaSet, and ClusterSet administration.
 - mysql   Support for connecting to MySQL servers using the classic MySQL
           protocol.
 - mysqlx  Used to work with X Protocol sessions using the MySQL X DevAPI.
 - os      Gives access to functions which allow to interact with the operating
           system.
 - plugins Plugin to manage MySQL Shell plugins
 - session Represents the currently open MySQL session.
 - shell   Gives access to general purpose functions and properties.
 - sys     Gives access to system specific parameters.
 - util    Global object that groups miscellaneous tools like upgrade checker
           and JSON import.

For additional information on these global objects use: .help()

EXAMPLES
\? AdminAPI
      Displays information about the AdminAPI.

\? \connect
      Displays usage details for the \connect command.

\? checkInstanceConfiguration
      Displays usage details for the dba.checkInstanceConfiguration function.

\? sql syntax
      Displays the main SQL help categories.
 MySQL  localhost:33060+  world_x  JS > 

请输入\help和命令名,获取MySQL Shell命令的详细帮助。例如,要查看\connect命令的帮助信息,输入:

 MySQL  localhost:33060+  world_x  JS > \help \connect
NAME
      \connect - Connects the shell to a MySQL server and assigns the global
      session.

SYNTAX
      \connect [] 
      \c [] 

DESCRIPTION
      TYPE is an optional parameter to specify the session type. Accepts the
      following values:

      - --mc, --mysql: create a classic MySQL protocol session (default port
        3306)
      - --mx, --mysqlx: create an X protocol session (default port 33060)
      - --ssh : create an SSH tunnel to use as a gateway for db
        connection. This requires that db port is specified in advance.

      If TYPE is omitted, automatic protocol detection is done, unless the
      protocol is given in the URI.

      URI format is: [user[:password]@]hostname[:port] and SSHURI format is:
      [user@]hostname[:port]

EXAMPLE
      \connect --mx root@localhost
            Creates a global session using the X protocol to the indicated URI.
 MySQL  localhost:33060+  world_x  JS > 

退出MySQL Shell
输入如下命令退出MySQL Shell:

 MySQL  localhost:33060+  world_x  JS > \quit