您的位置:首页 > 数据库 > Mongodb

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

2017-06-13 15:02 681 查看
 
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



2、RoboMongo



windows下64位 MongoDB安装工具和GUI工具
http://pan.baidu.com/s/1c2gqJGO
.NET MongoDB 驱动
http://pan.baidu.com/s/1eRZ1eNo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: