如何使用MongoDB API删除Azure CosmosDB中分区集合中的许多文档

问题描述 投票:1回答:1

请考虑以下文档类型

class Info
{
    public string Id { get; set; }
    public string UserId { get; set; }  // used as partition key
    public DateTime CreatedAt { get; set; }
}

我用这个创建了一个集合

var bson = new BsonDocument
{
    { "shardCollection", "mydb.userInfo" },
    { "key", new BsonDocument(shardKey, "hashed") }
};
database.RunCommand(new BsonDocumentCommand<BsonDocument>(bson));

要删除所有早于特定日期的文档,我试过这个

collection.DeleteManyAsync(t => t.CreatedAt >= date);

但这与Command delete failed: query in command must target a single shard key.失败了我的问题是,我应该如何在多个分区中有效地删除这些文档?在这种情况下,我不是在寻找如何选择分区键的答案。我认为总有一些情况我必须在所有分区上运行修改查询。

我可以首先使用collection.Find(t => t.CreatedAt >= date)查询文档,然后为每组分区键运行DeleteManyAsync(t => idsInThatPartition.Contains(t.Id) && t.UserId == thatPartitionKey),但我真的希望有更好的方法。示例代码:

var affectedPartitions = await collection.Aggregate()
    .Match(i => i.CreatedAt >= date)
    .Group(i => i.UserId, group => new { Key = group.Key })
    .ToListAsync();

foreach (var partition in affectedPartitions)
{
    await collection.DeleteManyAsync(
        i => i.CreatedAt >= date && i.UserId == partition.Key);
}
c# mongodb azure azure-cosmosdb mongodb-.net-driver
1个回答
0
投票

我遇到了同样的问题,最后发现目前还不行,Azure CosmosDb团队正在研究解决方案,暂定于2019年的第一个月发布

https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/34813063-cosmosdb-mongo-api-delete-many-with-partition-ke

等着瞧 :(

© www.soinside.com 2019 - 2024. All rights reserved.