7.1 將集合視為關聯式表格

希望將標準 SQL 資料行與文件一起儲存的應用程式可以將集合轉換為表格。在這種情況下,可以使用 Schema.getCollectionAsTable() 函式將集合提取為表格物件。從那一刻起,它就被視為常規表格。可以使用下列語法在 SQL CRUD 作業中存取文件值

doc->'$.field'

doc->'$.field' 用於存取文件最上層欄位。也可以指定更複雜的路徑。

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

一旦使用 Schema.getCollectionAsTable() 函式將集合提取為表格,就可以使用所有 SQL CRUD 作業。使用文件存取語法,您可以從集合的文件和額外的 SQL 資料行中選取資料。

以下範例顯示如何將 JSON 文件字串插入 doc 欄位。

// 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]);