文件首頁
X DevAPI 使用者指南
下載本手冊
PDF (US Ltr) - 1.4Mb
PDF (A4) - 1.4Mb


X DevAPI 使用者指南  /  使用文件  /  使用文件 ID

5.2 使用文件 ID

本節說明文件 ID 是什麼以及如何使用它。

每個文件都有一個稱為文件 ID 的唯一識別碼,可以將其視為資料表主鍵的等效項目。文件 ID 值通常在新增文件時由伺服器自動產生,但也可以手動指派。指派的文件 ID 會在 collection.add() 操作的 Result(Connector/J 的 AddResult)物件的 generatedIds 屬性中傳回,並且可以使用 getGeneratedIds() 方法存取。如需有關文件 ID 的更多背景資訊,請參閱第 5.3 節「瞭解文件 ID」

以下 JavaScript 程式碼範例顯示如何將文件新增至集合,擷取新增文件的 ID,並測試是否無法新增重複的 ID。

mysql-js > var result = mycollection.add({test:'demo01'}).execute()
mysql-js > print(result.generatedIds)
[
    "00006075f6810000000000000006"
]
mysql-js > var result = mycollection.add({test:'demo02'}).add({test:'demo03'}).execute()
mysql-js > print(result.generatedIds)
[
    "00006075f6810000000000000007",
    "00006075f6810000000000000008"
]

mysql-js > mycollection.find()
{
    "_id": "00006075f6810000000000000006",
    "test": "demo01"
}
{
    "_id": "00006075f6810000000000000007",
    "test": "demo02"
}
{
    "_id": "00006075f6810000000000000008",
    "test": "demo03"
}
3 documents in set (0.0102 sec)
mysql-js > var result = mycollection.add({_id:'00006075f6810000000000000008', test:'demo04'}).execute()
Document contains a field value that is not unique but required to be (MySQL Error 5116)

如以上範例所示,文件 ID 儲存在文件的 _id 欄位中。文件 ID 是最大長度為 32 個字元的 VARBINARY()。如果在建立文件時提供 _id,則會採用它;如果未提供 _id,則會自動為文件指派一個。

以下範例說明如何提供或自動產生 _id 值。假設 test 綱要存在並已指派給變數 db,集合 my_collection 存在且 custom_id 是唯一的。

MySQL Shell JavaScript 程式碼

// If the _id is provided, it will be honored
var result = myColl.add( { _id: 'custom_id', a : 1 } ).execute();
var document = myColl.find("a = 1").execute().fetchOne();
print("User Provided Id:", document._id);

// If the _id is not provided, one will be automatically assigned
result = myColl.add( { b: 2 } ).execute();
print("Autogenerated Id:", result.getGeneratedIds()[0]);

MySQL Shell Python 程式碼

# If the _id is provided, it will be honored
result = myColl.add( { '_id': 'custom_id', 'a' : 1 } ).execute()
document = myColl.find('a = 1').execute().fetch_one()
print("User Provided Id: %s" % document._id)

# If the _id is not provided, one will be automatically assigned
result = myColl.add( { 'b': 2 } ).execute()
print("Autogenerated Id: %s" % result.get_generated_ids()[0])

Node.js JavaScript 程式碼

// If the _id is provided, it will be honored
myColl.add({ _id: 'custom_id', a : 1 }).execute().then(function () {
  myColl.getOne('custom_id').then(function (doc) {
    console.log('User Provided Id:', doc._id);
  });
});

// If the _id is not provided, one will be automatically assigned
myColl.add({ b: 2 }).execute().then(function (result) {
  console.log('Autogenerated Id:', result.getGeneratedIds()[0]);
});

C# 程式碼

// If the _id is provided, it will be honored
var result = myColl.Add(new { _id = "custom_id", a = 1 }).Execute();
Console.WriteLine("User Provided Id:", result.AutoIncrementValue);

// If the _id is not provided, one will be automatically assigned
result = myColl.Add(new { b = 2 }).Execute();
Console.WriteLine("Autogenerated Id:", result.AutoIncrementValue);

Python 程式碼

# If the _id is provided, it will be honored
result = my_coll.add({'_id': 'custom_id', 'a': 1}).execute()
print("User Provided Id: {0}".format(result.get_last_document_id()))

# If the _id is not provided, one will be automatically assigned
result = my_coll.add({'b': 2}).execute()
print("Autogenerated Id: {0}".format(result.get_last_document_id()))

Java 程式碼

// If the _id is provided, it will be honored
AddResult result = coll.add("{\"_id\":\"custom_id\",\"a\":1}").execute();
System.out.println("User Provided Id:" + ((JsonString) coll.getOne("custom_id").get("_id")).getString());

// If the _id is not provided, one will be automatically assigned
result = coll.add("{\"b\":2}").execute();
System.out.println("Autogenerated Id:" + result.getGeneratedIds().get(0));

C++ 程式碼

// If the _id is provided, it will be honored
Result result = myColl.add(R"({ "_id": "custom_id", "a" : 1 })").execute();
std::vector<string> ids = result.getGeneratedIds();
if (ids.empty())
  cout << "No Autogenerated Ids" << endl;

// If the _id is not provided, one will be automatically assigned
result = myColl.add(R"({ "b": 2 })").execute();
ids = result.getGeneratedIds();
cout << "Autogenerated Id:" << ids[0] << endl;

某些文件具有自然的唯一鍵。例如,包含書籍清單的集合很可能會為代表書籍的每個文件包含國際標準書號 (ISBN)。ISBN 是長度為 13 個字元的字串,完全在 _id 欄位的 32 個字元長度限制內。

// using a book's unique ISBN as the object ID
myColl.add( {
_id: "978-1449374020",
title: "MySQL Cookbook: Solutions for Database Developers and Administrators"
}).execute();

使用 find() 從集合中擷取新插入的書籍,依其文件 ID 擷取。

var book = myColl.find('_id = "978-1449374020"').execute();

目前,X DevAPI 不支援使用隱含的 _id 以外的任何文件欄位作為文件 ID,沒有辦法定義另一個鍵來執行相同的功能。