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