PDF (US Ltr)
- 1.2Mb
PDF (A4)
- 1.2Mb
Working with collections of documents is straightforward when
using X DevAPI. The following example shows the basic usage of
CRUD operations (see
Section 4.3, “Collection CRUD Function Overview” for more
details) when working with documents: After establishing a
connection to a MySQL Server instance, a new collection that can
hold JSON documents is created and several documents are inserted.
Then, a find operation is executed to search for a specific
document from the collection. Finally, the collection is dropped
again from the database. The example assumes that the
test
schema exists and that the collection
my_collection
does not exist.
# Connecting to MySQL Server and working with a Collection
from mysqlsh import mysqlx
# Connect to server
mySession = mysqlx.get_session( {
'host': 'localhost', 'port': 33060,
'user': 'user', 'password': 'password'} )
myDb = mySession.get_schema('test')
# Create a new collection 'my_collection'
myColl = myDb.create_collection('my_collection')
# Insert documents
myColl.add({ 'name': 'Laurie', 'age': 19 }).execute()
myColl.add({ 'name': 'Nadya', 'age': 54 }).execute()
myColl.add({ 'name': 'Lukas', 'age': 32 }).execute()
# Find a document
docs = myColl.find('name like :param1 AND age < :param2') \
.limit(1) \
.bind('param1','L%') \
.bind('param2',20) \
.execute()
# Print document
doc = docs.fetch_one()
print(doc)
# Drop the collection
myDb.drop_collection('my_collection')