To work with the collections in a schema, use the
db
global object to access the current
schema. In this example we are using the
world_x
schema imported previously, and the
countryinfo
collection. Therefore, the format
of the operations you issue is
db.
,
where collection_name
.operationcollection_name
is the name of
the collection which the operation is executed against. In the
following examples, the operations are executed against the
countryinfo
collection.
Use the add()
method to insert one document
or a list of documents into an existing collection. Insert the
following document into the countryinfo
collection. As this is multi-line content, press
Enter twice to insert the document.
mysql-js> 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-js> 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, see
Understanding Document IDs.
See CollectionAddFunction for the full syntax definition.