标签:
<add key="MongoConn" value="mongodb://127.0.0.1:27017"/> <add key="Database" value="mytest"/>
public static MongoDatabase GetMongoDatabase() { MongoClient mongoClient = new MongoClient(ConfigurationManager.AppSettings["MongoConn"]); MongoServer mongoServer = mongoClient.GetServer(); return mongoServer.GetDatabase(ConfigurationManager.AppSettings["Database"]); }
可以指定,表中的实际字段名称
[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; }
//IMongoQuery query= Query.EQ("name", "hao"); 查询条件 MongoCursor<UserModel> res = MongoHelper.GetMongoDatabase().GetCollection("users").FindAllAs<UserModel>(); ViewData.Model = res; return View();
public ActionResult Insert(UserModel userModel) { WriteConcernResult res= MongoHelper.GetMongoDatabase().GetCollection("users").Insert(userModel); if (res.Ok) { return Json("添加成功",JsonRequestBehavior.AllowGet); } return Json("添加失败", JsonRequestBehavior.AllowGet); }
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);
可以使用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不能获取 要转成ObjectId userModel.Id=new ObjectId(Id); //save操作会根据id更新 有相同id更新 没有匹配的添加 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); }
标签:
原文地址:http://www.cnblogs.com/zhaoyihao/p/4914583.html