我需要每分钟更新100,000多个文档的字段,我发现我的i7,6GB RAM,SSD HD PC上的当前代码几乎没有 足够有效。据我所知,你不能用驱动程序进行批量更新(我从via Nuget运行最新版)
以下是我通过运行以下代码获得的结果(执行25,000次更新的时间):
正如预期的索引效果最好,我不确定为什么异步效率较低。即使使用索引这种方式在未来增长到超过100,000次更新/分钟可能会变得太慢。
这是FindOneAndReplaceAsync的预期行为吗?如果是这样,还有另一种方法可以获得更好的性能。我试图用MongoDB做一些不适合它的东西吗?
代码(MCVE准备好):
public class A
{
public A(string id)
{
customId = id;
TimeStamp = DateTime.UtcNow;
}
[BsonId]
[BsonIgnoreIfDefault]
ObjectId Id { get; set; }
public string customId { get; set; }
public double val { get; set; }
public DateTime TimeStamp { get; set; }
}
class Program
{
static IMongoCollection<A> Coll = new MongoClient("mongodb://localhost").GetDatabase("Test").GetCollection<A>("A");
static FindOneAndReplaceOptions<A,A> Options = new FindOneAndReplaceOptions<A, A> { IsUpsert = true, };
static void SaveDoc(A doc)
{
Coll.FindOneAndReplace(Builders<A>.Filter.Where(x => x.customId == doc.customId), doc, Options);
}
static void Main(string[] args)
{
var docs = Enumerable.Range(0, 25000).Select(x => new A(x.ToString()));
Stopwatch sw = new Stopwatch();
sw.Start();
docs.ToList().ForEach(x => SaveDoc(x));
sw.Stop();
Debug.WriteLine(sw.ElapsedMilliseconds);
}
}
答案 0 :(得分:3)
我认为问题与协议和网络延迟有关。每个Update
操作都有序列化和传输惩罚。您可以使用批量写入来优化批处理操作性能。
在你的情况下,它看起来像这样:
//create container for bulk operations
var operations = new List<WriteModel<BsonDocument>>();
//add batch tasks
operations.Add(new ReplaceOneModel<A>(new BsonDocument("customId", doc1.customId), doc1) { IsUpsert = true });
operations.Add(new ReplaceOneModel<A>(new BsonDocument("customId", doc2.customId), doc2) { IsUpsert = true });
//execute BulkWrite operation
collection.BulkWrite(operations, new BulkWriteOptions() { BypassDocumentValidation = true, IsOrdered = false });
我建议将每个BulkWrite
操作的批量大小限制为不超过1000个文档。 MongoDb对BSON文档大小(16MB)有限制,可能导致操作失败。当然,对于包含少量字段的简单文档,批量大小可以是10000甚至更多。
BypassDocumentValidation
和IsOrdered
选项也可以显着加快写入过程。
还有一件事......
您可以使用原始BsonDocuments而不是过滤器构建器来消除LINQ选择器处理和过滤解析惩罚。
//instead of this
Builders<A>.Filter.Where(x => x.customId == doc.customId)
//you can use BsonDocument
new BsonDocument("customId", doc.customId)
在命令执行之前,您的过滤器构建器将被序列化为完全相同的BSON文档。