获取 'query in command must target a single shard'

Getting 'query in command must target a single shard'

我有一个使用 Mongo API 的 CosmosDB 设置。我在文档的一个字段上有一个带有散列分片的集合。当我 运行 命令如 db.collection.removedb.collection.deleteMany 我得到以下错误。

Command deleteMany failed: query in command must target a single shard key.: {"message":"Command deleteMany failed: query in command must target a single shard key."}

我不确定如何在查询中提及分片键,因为我希望查询 运行 跨所有分片。

当你想要 运行 命令如 db.collection.removedb.collection.deleteMany.

时,你需要提供分片键

例如:

我的数据来源如下:

[
    {
        "id" : "2",
        "name" : "b"
    },
    {
        "id" : "1",
        "name" : "a"
    }
]

我的共享密钥是 "/name"。使用 db.coll.deleteMany({"name":"a"}) 删除特定碎片。

希望对你有帮助。

应该是创建cosmosDb集合时选择的ShardKey。

FilterDefinition<Product> filter = Builders<Product>.Filter.Eq("id", 2);
=== 2 是我的 shardKey

await this._dbContext.GetProducts.DeleteOneAsync(filter);
return RedirectToAction("Index");

请参考下图,它在 CosmosDB 中的样子如何

在代码中指定架构模型时必须提供分片键(分区键)。一旦提供,我们就可以像往常一样执行保存、更新和删除等常规操作。

示例:

const mySchema = new Schema({
    requestId: { type: String, required: true },
    data: String,
    documents: [{ docId: String, name: String, attachedBy: String }],
    updatedBy: {
        type: {
            name: { type: String, required: true },
            email: { type: String, required: true },
        }, required: true
    },
    createdDate: { type: Date, required: true },
    updatedDate: { type: Date },
}, { shardKey: { requestId: 1 } }
);

在上面的代码中我们将requestId指定为Shard Key,现在我们可以执行任何mongo操作 示例:

let request:any = await myModel.findById(requestId);
request.data ="New Data";
await request.save();

希望对您有所帮助。

这适用于所有 Mongo 操作