本节介绍什么是文档 ID 以及如何使用它。
每个文档都有一个唯一的标识符,称为文档 ID,可以将其视为表的等效主键。文档 ID 值通常在添加文档时由服务器自动生成,但也可以手动分配。分配的文档 ID 会在 collection.add()
操作的 Result
(AddResult
针对 Connector/J) 对象的 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 是一个VARBINARY()
,最大长度为 32 个字符。如果在创建文档时提供了 _id
,则会保留该 ID;如果未提供 _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,无法定义其他键来执行相同的函数。