【问题标题】:Performance difference between MongoServer.Create() and mongoClient.GetServer() in MongoDbMongoDb 中 MongoServer.Create() 和 mongoClient.GetServer() 的性能差异
【发布时间】:2013-10-27 06:25:12
【问题描述】:

考虑这段代码:

     MongoServer mongo = MongoServer.Create();
        mongo.Connect();

        Console.WriteLine("Connected");
        Console.WriteLine();

        MongoDatabase db = mongo.GetDatabase("tutorial");
        Stopwatch stopwatch=new Stopwatch();
        stopwatch.Start();
        using (mongo.RequestStart(db))
        {
            MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("books");

            for (int i = 0; i < 100000; i++)
            {
                var nested = new BsonDocument
                {
                    {"name", "John Doe"},

                };
                collection.Insert(nested);
            }
        }
        stopwatch.Stop();
        Console.WriteLine(stopwatch.ElapsedMilliseconds);

        Console.ReadLine();

在第一行中,我使用了已过时的 MongoServer.Create()。但是在上面运行代码时,输​​出时间是 3056(大约 3 秒)。

所以我使用 MongoDb 文档推荐的这段代码。

 MongoClient mongo = new MongoClient();
            var server = mongo.GetServer();

            MongoDatabase db = server.GetDatabase("tutorial");
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            using (server.RequestStart(db))
            {
                MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("books");

                for (int i = 0; i < 100000; i++)
                {
                    var nested = new BsonDocument
                    {
                        {"name", "John Doe"},

                    };
                    collection.Insert(nested);
                }
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);

            Console.ReadLine();

当运行上面的代码时,输​​出时间是14225(在我的电脑上大约是 10 到 14 秒)。 为什么我在新版本的 mongoDb 上重构代码后得到了这个性能时间。我缺少什么?

【问题讨论】:

    标签: c# performance mongodb


    【解决方案1】:

    当您使用推荐的连接模式时(正如您在第二个示例中所做的那样),您很可能会看到在较新的驱动程序中默认启用写关注之间的区别。

    更改于 2012 年 11 月进行:

    http://docs.mongodb.org/manual/release-notes/drivers-write-concern/

    在此更改之前,默认情况下不会确认写入,因此您会看到“更快”的写入。

    关于 C# 更改 here 的更多细节。

    如果您想尝试新样式的连接,您可以在测试中禁用数据库连接的 WriteConcern:

    MongoDatabase db = server.GetDatabase("tutorial", WriteConcern.Unacknowledged);
    

    然后重新运行测试以比较性能。

    【讨论】:

    • 这正是我想要的。使用 WriteConcern.Unacknowledged 集我得到了相同的性能。谢谢。
    猜你喜欢
    • 2016-04-26
    • 2011-01-21
    • 2012-04-14
    • 2019-12-04
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多