namespace MongoDBTest { using System; using System.Collections.Generic; using System.Linq; using System.Text; using MongoDB.Driver; using MongoDB.Bson; internal class LoginDemo { MongoDatabase db; MongoCollection collections; public LoginDemo() { MongoServerSettings set = new MongoServerSettings() { Server = new MongoServerAddress("127.0.0.1") }; MongoServer server = new MongoServer(set); db = server.GetDatabase("mydb"); collections = db.GetCollection("login"); } ////// 单个对象插入 /// public void InsertLogin() { var Time = DateTime.Now.ToUniversalTime(); //实例一 添加匿名对象 var login = new { _id = "newid_100002", time = Time, userid = 10002, sessionid = "20110829215102", ip = "192.168.0.2", title = "注册", url = "Register.aspx" }; collections.Insert(login);//插入成功 //添加一个BsonDocument对象 BsonDocument doc = new BsonDocument(); doc.Add("_id", BsonValue.Create("newid_100003")); doc.Add("time", BsonValue.Create(Time)); doc.Add("userid", BsonValue.Create(10003)); doc.Add("sessionid", BsonValue.Create("20110829215103")); doc.Add("ip", BsonValue.Create("192.168.0.3")); doc.Add("title", BsonValue.Create("注册")); doc.Add("url", BsonValue.Create("Register.aspx")); collections.Insert(doc);//插入成功 //添加一个对象 Login man = new Login(); man._id = "newid_100004"; man.time = Time; man.userid = 10004; man.sessionid = "20110829215104"; man.ip = "192.168.0.4"; man.title = "注册"; man.url = "Register.aspx"; collections.Insert(man);//插入成功 } ////// 批量插入 /// public void InsertBatchLogin() { var Time = DateTime.Now.ToUniversalTime(); Listlogins = new List (); for (int i = 0; i < 100; i++) { Login man = new Login(); man._id = "newid_100001" + i.ToString();//_id在批量插入的时候不能重复,如果有一个重复全部集合无法插入到集合 man.time = Time; man.userid = 10004 + i; man.sessionid = "20110829215104"; man.ip = "192.168.0.4"; man.title = "注册"; man.url = "Register.aspx"; logins.Add(man); } collections.InsertBatch(typeof(Login), logins); //插入成功 } } public class Login { public string _id { get; set; } public DateTime time { get; set; } public int userid { get; set; } public string sessionid { get; set; } public string ip { get; set; } public string title { get; set; } public string url { get; set; } } }