MySQL 8.4 发行说明
要使用模式中的集合,请使用 db
全局对象访问当前模式。在此示例中,我们使用之前导入的 world_x
模式和 countryinfo
集合。因此,您发出的操作的格式为 db.
,其中 collection_name
.operationcollection_name
是执行操作的集合的名称。在以下示例中,操作是在 countryinfo
集合上执行的。
使用 add()
方法将一个文档或一个文档列表插入到现有集合中。将以下文档插入到 countryinfo
集合中。由于这是多行内容,请按两次 Enter 键插入文档。
Press CTRL+C to copymysql-py> db.countryinfo.add( { "GNP": .6, "IndepYear": 1967, "Name": "Sealand", "Code:": "SEA", "demographics": { "LifeExpectancy": 79, "Population": 27 }, "geography": { "Continent": "Europe", "Region": "British Islands", "SurfaceArea": 193 }, "government": { "GovernmentForm": "Monarchy", "HeadOfState": "Michael Bates" } } )
该方法返回操作的状态。您可以通过搜索文档来验证操作。例如
Press CTRL+C to copymysql-py> db.countryinfo.find("Name = 'Sealand'") { "GNP": 0.6, "_id": "00005e2ff4af00000000000000f4", "Name": "Sealand", "Code:": "SEA", "IndepYear": 1967, "geography": { "Region": "British Islands", "Continent": "Europe", "SurfaceArea": 193 }, "government": { "HeadOfState": "Michael Bates", "GovernmentForm": "Monarchy" }, "demographics": { "Population": 27, "LifeExpectancy": 79 } }
请注意,除了添加文档时指定的字段之外,还有一个额外的字段 _id
。每个文档都需要一个名为 _id
的标识符字段。_id
字段的值在同一个集合中的所有文档中必须是唯一的。文档 ID 由服务器生成,而不是由客户端生成,因此 MySQL Shell 不会自动设置 _id
值。如果文档不包含 _id
字段,MySQL 会设置 _id
值。有关更多信息,请参阅 了解文档 ID。
有关完整语法定义,请参阅 CollectionAddFunction。
有关更多信息,请参阅 了解文档 ID。