Documentation Home
MySQL 9.2 Reference Manual
Related Documentation Download this Manual
PDF (US Ltr) - 40.8Mb
PDF (A4) - 40.9Mb
Man Pages (TGZ) - 259.7Kb
Man Pages (Zip) - 366.9Kb
Info (Gzip) - 4.1Mb
Info (Zip) - 4.1Mb


22.4.3.2 Working with Collections

To work with the collections in a schema, use thedb global object to access the current schema. In this example we are using theworld_x schema imported previously, and thecountryinfo collection. Therefore, the format of the operations you issue isdb.collection_name.operation, wherecollection_name is the name of the collection which the operation is executed against. In the following examples, the operations are executed against thecountryinfo collection.

Add a Document

Use theadd() method to insert one document or a list of documents into an existing collection. Insert the following document into thecountryinfo collection. As this is multi-line content, pressEnter twice to insert the document.

mysql-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"    }  })

The method returns the status of the operation. You can verify the operation by searching for the document. For example:

mysql-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    }}

Note that in addition to the fields specified when the document was added, there is one more field, the_id. Each document requires an identifier field called_id. The value of the_id field must be unique among all documents in the same collection. Document IDs are generated by the server, not the client, so MySQL Shell does not automatically set an_id value. MySQL sets an_id value if the document does not contain the_id field. For more information, seeUnderstanding Document IDs.

Related Information