MongoDB 3.4版本, C# 驱动 2.4 操作

时间:2023-03-09 20:44:58
MongoDB 3.4版本, C# 驱动 2.4 操作
 private static string _connStr = "mongodb://127.0.0.1:27017";
private static string _dbName = "test";
const string CollectionName = "sun";
  private static IMongoDatabase db
{
get
{
var url = new MongoUrl(_connStr);
var client = new MongoClient(url);
return client.GetDatabase(_dbName);
}
}
            //数据库连接字符串
#region //获取表对象
IMongoCollection<Video> tb = db.GetCollection<Video>(CollectionName); //先删除当前表
tb.Database.DropCollection(CollectionName); //测试数据---------------------------------
var videos = new List<Video>
{
new Video { Title="The Perfect Developer",
Category="SciFi", Minutes=118 },
new Video { Title="Lost In Frankfurt am Main",
Category="Horror", Minutes=122 },
new Video { Title="The Infinite Standup",
Category="Horror", Minutes=341 }
};
//测试数据--------------------------------- //插入
tb.InsertMany(videos); //查询
var all = tb.Find(x => x.Title != string.Empty).ToList(); //分组查询
var groupby = tb.Aggregate()
.Group(x => x.Category, g => new { Name = g.Key, Count = g.Count(), TotalMinutes = g.Sum(x => x.Minutes) })
.ToList(); //更新
// updating title with "The perfect developer" video's 'title' and 'minute'
tb.FindOneAndUpdate(x => x.Title == "The Perfect Developer",
Builders<Video>.Update.Set(x => x.Title, "A Perfect Developer [updated]")
.AddToSet(x => x.Comments, "good video!")
.AddToSet(x => x.Comments, "not bad")
); all = tb.Find(x => x.Title != string.Empty).ToList(); //删除
tb.DeleteOne(x => x.Minutes == 122); all = tb.Find(x => x.Title != string.Empty).ToList(); #endregion

.

推荐使用2个MongoDB的 GUI

1、MongoDBCompass

MongoDB 3.4版本, C# 驱动 2.4 操作

2、RoboMongo

MongoDB 3.4版本, C# 驱动 2.4 操作

windows下64位 MongoDB安装工具和GUI工具

http://pan.baidu.com/s/1c2gqJGO

.NET MongoDB 驱动

http://pan.baidu.com/s/1eRZ1eNo