X DevAPI 用户指南  / 第 7 章 使用关系表和文档  /  7.1 集合作为关系表

7.1 集合作为关系表

寻求使用文档存储标准 SQL 列的应用程序可以将集合转换为表。Schema.getCollectionAsTable()在这种情况下,可以使用该函数将集合作为 Table 对象获取 。从那一刻起,它就被视为一张普通桌子。可以使用以下语法在 SQL CRUD 操作中访问文档值:

doc->'$.field'

doc->'$.field'用于访问文档顶级字段。也可以指定更复杂的路径。

doc->'$.some.field.like[3].this'

一旦使用函数将集合提取为表, Schema.getCollectionAsTable()就可以使用所有 SQL CRUD 操作。使用文档访问语法,您可以从集合文档和额外的 SQL 列中选择数据。

以下示例显示如何将 JSON 文档字符串插入到doc字段中。

MySQL 外壳 JavaScript 代码

// Get the customers collection as a table
var customers = db.getCollectionAsTable('customers');
customers.insert('doc').values('{"_id":"001", "name": "Ana", "last_name": "Silva"}').execute();

// Now do a find operation to retrieve the inserted document
var result = customers.select(["doc->'$.name'", "doc->'$.last_name'"]).where("doc->'$._id' = '001'").execute();

var record = result.fetchOne();

print ("Name : "  + record[0]);
print ("Last Name : "  + record[1]);

MySQL 外壳 Python 代码

# Get the customers collection as a table
customers = db.get_collection_as_table('customers')
customers.insert('doc').values('{"_id":"001", "name": "Ana", "last_name": "Silva"}').execute()

# Now do a find operation to retrieve the inserted document
result = customers.select(["doc->'$.name'", "doc->'$.last_name'"]).where("doc->'$._id' = '001'").execute()

record = result.fetch_one()

print("Name : %s\n"  % record[0])
print("Last Name : %s\n"  % record[1])

Node.js JavaScript 代码

// Get the customers collection as a table
var customers = db.getCollectionAsTable('customers');
customers.insert('doc').values('{"_id":"001", "name": "Ana"}').execute();

C#代码

// Get the customers collection as a table
var customers = db.GetCollectionAsTable("customers");
customers.Insert("doc").Values("{ \"_id\": 1, \"name\": \"Ana\" }").Execute();

Python代码

# Get the customers collection as a table
customers = db.get_collection_as_table("customers")
customers.insert('doc').values({'_id':'001', 'name': 'Ana', 'last_name': 'Silva'}).execute()

# Now do a find operation to retrieve the inserted document
result = customers.select(["doc->'$.name'", "doc->'$.last_name'"]).where("doc->'$._id' = '001'").execute()

record = result.fetch_one()

print('Name : {0}'.format(record[0]))
print('Last Name : {0}'.format(record[1]))

Java代码

// Get the customers collection as a table
Table customers = db.getCollectionAsTable("customers");
customers.insert("doc").values("{\"name\": \"Ana\"}").execute();

C++代码

// Get the customers collection as a table
Table customers = db.getCollectionAsTable("customers");
customers.insert("doc")
         .values(R"({"_id":"001", "name": "Ana", "last_name": "Silva"})").execute();

// Now do a find operation to retrieve the inserted document
RowResult result = customers.select("doc->'$.name'", "doc->'$.last_name'")
                            .where("doc->'$._id' = '001'").execute();

Row record = result.fetchOne();
cout << "Name : " << record[0] << endl;
cout << "Last Name : " << record[1] << endl;