日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Mongodb基本操作之.net

發(fā)布時(shí)間:2025/1/21 编程问答 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。