X DevAPI 用户指南  / 第 5 章使用文档  /  5.2 使用文档 ID

5.2 使用文档 ID

本节介绍什么是文档 ID 以及如何使用它。

每个文档都有一个称为文档 ID 的唯一标识符,可以将其视为等同于表的主键。文档ID值通常在添加文档时由服务器自动生成,但也可以手动分配。分配的文档 ID 在 操作的(对于连接器/J)对象的generatedIds属性中 返回, 并且可以使用该 方法访问。有关文档 ID 的更多背景信息,请参阅 第 5.3 节,“了解文档 ID”ResultAddResultcollection.add()getGeneratedIds()

以下 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 是 VARBINARY()最大长度为 32 个字符的 a。如果_id在创建文档时提供了 ,则表示尊重;如果没有_id 提供,一个将自动分配给文档。

以下示例说明了如何_id 提供或自动生成该值。假设test模式存在并分配给变量db,集合 my_collection存在并且 custom_id是唯一的。

MySQL 外壳 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 外壳 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 个字符的字符串,完全在该字段的 32 个字符的长度限制内_id

// 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 之外的任何文档字段——无法定义另一个键来执行相同的功能。