使用 MongoDB API,我们无法通过 .NET MongoDB 驱动程序创建具有自定义数据库名称的分片集合。
命令:
{"shardCollection", $"{MongoDatabase.DatabaseNamespace.DatabaseName}.{collectionName}"}
{"key", new BsonDocument {{"ShardKey1", "hashed"}}}
低于异常,
{"Command shardCollection failed: shardCollection must be run against the admin database."}
只能在名为“admin”的数据库上创建分片集合。
cosmos db 似乎更愿意使用自定义命令。这对我有用:
var createCollectionCommand = new BsonDocument
{
{ "customAction", "CreateCollection" },
{ "collection", collection },
{ "shardKey", shardkey }
};
await _db.RunCommandAsync<BsonDocument>(createCollectionCommand);
升级到.net mongodb驱动程序3.6+后出现语义已经改变了一点,试试这个:
IMongoDatabase db;
var bson = new BsonDocument
{
{ "customAction", "CreateCollection" },
{ "collection", collectionName },
{ "shardKey", partitionKey },
{ "offerThroughput", 400 },
};
var shellCommand = new BsonDocumentCommand<BsonDocument>(bson);
db = connectionSet.MongoClient.GetDatabase(cosmosDbName);
var commandResult = db.RunCommand<BsonDocument>(shellCommand);
然后,根据您是否有自动缩放功能,您可能需要指定它,请查看此处 https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/custom-commands