PDF (US Ltr) - 1.4Mb
PDF (A4) - 1.4Mb
希望将标准 SQL 列与文档一起存储的应用程序可以将集合转换为表。在这种情况下,可以使用 Schema.getCollectionAsTable()
函数将集合获取为表对象。从那一刻起,它就被视为常规表。可以使用以下语法在 SQL CRUD 操作中访问文档值
doc->'$.field'
doc->'$.field'
用于访问文档顶级字段。也可以指定更复杂的路径。
doc->'$.some.field.like[3].this'
使用 Schema.getCollectionAsTable()
函数将集合获取为表后,可以使用所有 SQL CRUD 操作。使用文档访问语法,您可以从集合的文档和额外的 SQL 列中选择数据。
以下示例演示如何将 JSON 文档字符串插入 doc
字段。
MySQL Shell 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 Shell 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;