X DevAPI 用户指南  / 第 4 章使用集合  /  4.1 集合的基本 CRUD 操作

4.1 集合的基本 CRUD 操作

使用 X DevAPI 时,处理文档集合非常简单。以下示例显示了在处理文档时 CRUD 操作的基本用法(有关更多详细信息,请参见 第 4.3 节“集合 CRUD 功能概述”): 建立与 MySQL 服务器实例的连接后,将创建一个可以保存 JSON 文档的新集合并插入了几个文档。然后,执行查找操作以从集合中搜索特定文档。最后,该集合再次从数据库中删除。该示例假定 test模式存在并且集合 my_collection不存在。

MySQL 外壳 JavaScript 代码

// Connecting to MySQL Server and working with a Collection

var mysqlx = require('mysqlx');

// Connect to server
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password'} );

var myDb = mySession.getSchema('test');

// Create a new collection 'my_collection'
var myColl = myDb.createCollection('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
var docs = myColl.find('name like :param1 AND age < :param2').limit(1).
        bind('param1','L%').bind('param2',20).execute();

// Print document
print(docs.fetchOne());

// Drop the collection
myDb.dropCollection('my_collection');

MySQL 外壳 Python 代码

# 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')

Node.js JavaScript 代码

// --------------------------------------------------
// Connecting to MySQL Server and working with a Collection
var mysqlx = require('@mysql/xdevapi');
var db;

// Connect to server
mysqlx
  .getSession({
    user: 'user',
    password: 'password',
    host: 'localhost',
    port: '33060',
  })
  .then(function (session) {
    db = session.getSchema('test');
    // Create a new collection 'my_collection'
    return db.createCollection('my_collection');
  })
  .then(function (myColl) {
    // Insert documents
    return Promise
      .all([
        myColl.add({ name: 'Laurie', age: 19 }).execute(),
        myColl.add({ name: 'Nadya', age: 54 }).execute(),
        myColl.add({ name: 'Lukas', age: 32 }).execute()
      ])
      .then(function () {
        // Find a document
        return myColl
            .find('name like :name && age < :age')
            .bind({ name: 'L%', age: 20 })
            .limit(1)
            .execute(function (doc) {
              // Print document
              console.log(doc);
            });
      });
  })
  .then(function(docs) {
    // Drop the collection
    return db.dropCollection('my_collection');
  })
  .catch(function(err) {
    // Handle error
  });

C#代码

// Connecting to MySQL Server and working with a Collection

// Connect to server
var mySession = MySQLX.GetSession("server=localhost;port=33060;user=user;password=password;");

var myDb = mySession.GetSchema("test");

// Create a new collection "my_collection"
var myColl = myDb.CreateCollection("my_collection");

// Insert documents
myColl.Add(new { name = "Laurie", age = 19 }).Execute();
myColl.Add(new { name = "Nadya", age = 54 }).Execute();
myColl.Add(new { name = "Lukas", age = 32 }).Execute();

// Find a document
var docs = myColl.Find("name like :param1 AND age < :param2").Limit(1)
.Bind("param1", "L%").Bind("param2", 20).Execute();

// Print document
Console.WriteLine(docs.FetchOne());

// Drop the collection
myDb.DropCollection("my_collection");

Python代码

# Connecting to MySQL Server and working with a Collection

import mysqlx

# Connect to server
my_session = mysqlx.get_session({
    'host': 'localhost', 'port': 33060,
    'user': 'user', 'password': 'password'
})

my_schema = my_session.get_schema('test')

# Create a new collection 'my_collection'
my_coll = my_schema.create_collection('my_collection')

# Insert documents
my_coll.add({ 'name': 'Laurie', 'age': 19 }).execute()
my_coll.add({ 'name': 'Nadya', 'age': 54 }).execute()
my_coll.add({ 'name': 'Lukas', 'age': 32 }).execute()

# Find a document
docs = my_coll.find('name like :param1 AND age < :param2') \
    .limit(1) \
    .bind('param1', 'L%') \
    .bind('param2', 20) \
    .execute()

# Print document
doc = docs.fetch_one()
print("Name: {0}".format(doc['name']))
print("Age: {0}".format(doc['age]))

# Drop the collection
my_session.drop_collection('test', 'my_collection')

Java代码

// Connect to server
Session mySession = new SessionFactory().getSession("mysqlx://localhost:33060/test?user=user&password=password");

Schema myDb = mySession.getSchema("test");

// Create a new collection 'my_collection'
Collection myColl = myDb.createCollection("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
DocResult docs = myColl.find("name like :name AND age < :age")
        .bind("name", "L%").bind("age", 20).execute();

// Print document
DbDoc doc = docs.fetchOne();
System.out.println(doc);

// Drop the collection
myDb.dropCollection("my_collection");

C++代码

// Connecting to MySQL Server and working with a Collection

#include <mysqlx/xdevapi.h>

// Connect to server
Session session(33060, "user", "password");
Schema db = session.getSchema("test");

// Create a new collection 'my_collection'
Collection myColl = db.createCollection("my_collection");

// Insert documents
myColl.add(R"({ "name": "Laurie", "age": 19 })").execute();
myColl.add(R"({ "name": "Nadya", "age": 54 })").execute();
myColl.add(R"({ "name": "Lukas", "age": 32 })").execute();

// Find a document
DocResult docs = myColl.find("name like :param1 AND age < :param2").limit(1)
                        .bind("param1","L%").bind("param2",20).execute();

// Print document
cout << docs.fetchOne();

// Drop the collection
db.dropCollection("my_collection");