Mongodb基本操作之.net
生活随笔
收集整理的這篇文章主要介紹了
Mongodb基本操作之.net
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、下載官方for C#驅(qū)動(dòng)
2、導(dǎo)入2個(gè)dll文件
3、連接字符串
<add key="MongoConn" value="mongodb://127.0.0.1:27017"/><add key="Database" value="mytest"/>4、獲取MongoDatabase對(duì)象
public static MongoDatabase GetMongoDatabase(){MongoClient mongoClient = new MongoClient(ConfigurationManager.AppSettings["MongoConn"]);MongoServer mongoServer = mongoClient.GetServer();return mongoServer.GetDatabase(ConfigurationManager.AppSettings["Database"]);}5、新建Model對(duì)象
可以指定,表中的實(shí)際字段名稱
[BsonElement("_id")]public ObjectId Id { get; set; }[BsonElement("name")]public string Name { get; set; }[BsonElement("sex")]public string Sex { get; set; }[BsonElement("sec")]public string Sec { get; set; }[BsonElement("sd")]public string Sd { get; set; }[BsonElement("age")]public int Age { get; set; }?
6、查詢
//IMongoQuery query= Query.EQ("name", "hao"); 查詢條件MongoCursor<UserModel> res = MongoHelper.GetMongoDatabase().GetCollection("users").FindAllAs<UserModel>();ViewData.Model = res;return View();7、插入封裝的Model對(duì)象
public ActionResult Insert(UserModel userModel){WriteConcernResult res= MongoHelper.GetMongoDatabase().GetCollection("users").Insert(userModel);if (res.Ok){return Json("添加成功",JsonRequestBehavior.AllowGet);}return Json("添加失敗", JsonRequestBehavior.AllowGet);}8、根據(jù)objectId刪除
IMongoQuery query = Query.EQ("_id", new BsonObjectId(id));WriteConcernResult res= MongoHelper.GetMongoDatabase().GetCollection("users").Remove(query);if (res.Ok){return Json("刪除成功", JsonRequestBehavior.AllowGet);}return Json("刪除失敗", JsonRequestBehavior.AllowGet);9、更新數(shù)據(jù)
可以使用save方法或者update方法,save方法比較方便。
public ActionResult Edit(string id){UserModel res =MongoHelper.GetMongoDatabase().GetCollection("users").FindOneByIdAs<UserModel>(new BsonObjectId(id));ViewData.Model = res;return View();}[HttpPost]public ActionResult Edit(UserModel userModel,string Id){ //此處UserModel的id不能獲取 要轉(zhuǎn)成ObjectIduserModel.Id=new ObjectId(Id);//save操作會(huì)根據(jù)id更新 有相同id更新 沒(méi)有匹配的添加WriteConcernResult res = MongoHelper.GetMongoDatabase().GetCollection("users").Save(userModel);//也可使用下面的方法//WriteConcernResult res = MongoHelper.GetMongoDatabase().GetCollection("users").Update(Query.EQ("_id", new BsonObjectId(userModel.Id)), new UpdateDocument(userModel.ToBsonDocument()));if (res.Ok){return Json("更新成功", JsonRequestBehavior.AllowGet);}return Json("更新失敗", JsonRequestBehavior.AllowGet);}?
轉(zhuǎn)載于:https://www.cnblogs.com/zhaoyihao/p/4914583.html
總結(jié)
以上是生活随笔為你收集整理的Mongodb基本操作之.net的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: FPGA综合优化
- 下一篇: Reactive Cocoa实践举例