MongoDB API 的分片键和 Azure CosmosDB
Shard key and Azure CosmosDB for MongoDB API
我创建了一个使用 MongoDB 的 Python SDK 的 CosmosDB 数据库,我们将数据库称为 school
,将集合称为 students
。在创建数据库时,Azure UI 让我创建一个无限存储容量的分片键,我们称之为 school.students
。
我正在使用 pymongo
添加以下文档:
{
"id": "abc123",
"name": "jack"
}
代码为:
from pymongo import MongoClient
student_data = {
"id": "abc123",
"name": "jack"
}
client = MongoClient("mongodb://...")
db = client["school"]
collection = db["students"]
collection.insert_one(student_data)
当我选择10GB的存储时,我添加文档没问题,但是当我选择unlimited option with shard key时,出现以下错误:
pymongo.errors.WriteError: document does not contain shard key at 'school.students'
问题是,我应该在哪里使用分片键?以及如何克服这个问题?
您可以通过 mongo shell
创建 collection
db.runCommand( { shardCollection: "myDb.students", key: { id: "hashed" } } )
MongoDB 中的 shard key
映射到 Cosmos DB 中的 partition key
。创建集合时,如果您是通过门户创建的,系统会要求您指定 分区键 。或者您可以通过 MongoDB 的命令行工具或通过代码指定分片键(然后称为 分片键 )。该分片键必须存在于您的文档中。
在你的例子中,你的文档只包含 id
和 name
(你可以使用其中任何一个作为你的片键)。或者,您可以指定一个额外的 属性 作为您的分片键。例如,也许 schoolid
:
student_data = {
"id": "abc123",
"name": "jack",
"schoolid": "school1"
}
创建集合时,您需要指定 schoolid
作为分区键。此时,您的文档保存将起作用,因为您的文档中将包含一个分片键(分区键)。
在您的原始示例中,您指定 school.students
作为您的分片键。这将需要你有一个名为 school
的 属性 和一个名为 students
的子 属性 (我猜这样做没有多大意义):
student_data = {
"id": "abc123",
"name": "jack",
"school": {
"students": ...
}
}
我创建了一个使用 MongoDB 的 Python SDK 的 CosmosDB 数据库,我们将数据库称为 school
,将集合称为 students
。在创建数据库时,Azure UI 让我创建一个无限存储容量的分片键,我们称之为 school.students
。
我正在使用 pymongo
添加以下文档:
{
"id": "abc123",
"name": "jack"
}
代码为:
from pymongo import MongoClient
student_data = {
"id": "abc123",
"name": "jack"
}
client = MongoClient("mongodb://...")
db = client["school"]
collection = db["students"]
collection.insert_one(student_data)
当我选择10GB的存储时,我添加文档没问题,但是当我选择unlimited option with shard key时,出现以下错误:
pymongo.errors.WriteError: document does not contain shard key at 'school.students'
问题是,我应该在哪里使用分片键?以及如何克服这个问题?
您可以通过 mongo shell
创建 collectiondb.runCommand( { shardCollection: "myDb.students", key: { id: "hashed" } } )
MongoDB 中的 shard key
映射到 Cosmos DB 中的 partition key
。创建集合时,如果您是通过门户创建的,系统会要求您指定 分区键 。或者您可以通过 MongoDB 的命令行工具或通过代码指定分片键(然后称为 分片键 )。该分片键必须存在于您的文档中。
在你的例子中,你的文档只包含 id
和 name
(你可以使用其中任何一个作为你的片键)。或者,您可以指定一个额外的 属性 作为您的分片键。例如,也许 schoolid
:
student_data = {
"id": "abc123",
"name": "jack",
"schoolid": "school1"
}
创建集合时,您需要指定 schoolid
作为分区键。此时,您的文档保存将起作用,因为您的文档中将包含一个分片键(分区键)。
在您的原始示例中,您指定 school.students
作为您的分片键。这将需要你有一个名为 school
的 属性 和一个名为 students
的子 属性 (我猜这样做没有多大意义):
student_data = {
"id": "abc123",
"name": "jack",
"school": {
"students": ...
}
}