mongodb的数据插入速度是其一个亮点,同样的10000条数据,插入的速度要比Mysql和sqlserver都要快,当然这也是要看使用者怎么个使用法,你代码如果10000次写入使用10000次连接,那也是比不过其他数据库使用事务一次性提交的速度的。

同样,mongo也提供的一次性插入巨量数据的方法,因为mongodb没有事务这回事,所以在在C#驱动里,具体方法是InsertManyAsync()一次性插入多个文档。与之对应的是InsertOneAsync,这个是一次插入一个文档;
InsertManyAsync()这个方法带入的参数只要是实现了IEnumerable接口的类型就可以,所以可是list<>,这样的数据类型;
同样的10000次插入,两个方法时间差别很大。如图:

使用一次性插入多个文档方法,插入10000条耗时仅1.3秒,分成10000次插入,耗时19.9秒。区别大了个去。同样,前面我做过使用mysql插入10000条记录,要用4秒多,可见,这mongodb插入速度不是吹 的。
具体的代码如下,贴上:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Diagnostics;
namespace sqltomongo
{
public class MongoHelp
{
private static IMongoClient client
{
get
{
if (null == _client)
{
_client = new MongoClient("mongodb://127.0.0.1:27017");
}
return _client;
}
}
public static IMongoDatabase database
{
get {
_database = client.GetDatabase("HotelPersonInfo");
return _database;
}
set {
_database = value;
}
}
public static IMongoCollection collection
{
get {
return _collection;
}
set {
_collection = value;
}
}
protected static IMongoClient _client;
protected static IMongoDatabase _database;
protected static IMongoCollection _collection;
//测试效率,两个方法用时比较
public async static void TestMongo()
{
//自定义的对象
RoomInfo roomdata = new RoomInfo();
List docunemts = new List();
collection = database.GetCollection("HotelPersonInfo");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 1; i < 10000; i++)
{
//mongo对用户自定义的对象扩展了tobasonDocument这个方法,可直接用
var roomdatadocument = new BsonDocument(roomdata.ToBsonDocument());
docunemts.Add(roomdatadocument);
}
//一次10000条
//这方法 查看api手册,只要实现了IEnumerable借口的类型就都行
await collection.InsertManyAsync(docunemts);
sw.Stop();
TimeSpan ts2 =sw.Elapsed;
Console.WriteLine("total is " + ts2.TotalMilliseconds);
///一次次插 10000次
Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int i = 1; i < 10000; i++)
{
var roomdatadocument = new BsonDocument(roomdata.ToBsonDocument());
await collection.InsertOneAsync(roomdatadocument);
}
sw2.Stop();
TimeSpan ts22 = sw2.Elapsed;
Console.WriteLine("total is " + ts22.TotalMilliseconds);
// await collection.InsertOneAsync(roomdatadocument);
//collection = database.GetCollection("HotelPersonInfo");
// collection.InsertOneAsync(roomdatadocument);
}
}
} 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。