1、下载官方for C#驱动
2、导入2个dll文件
3、连接字符串
<add key="MongoConn" value="mongodb://127.0.0.1:27017"/>
<add key="Database" value="mytest"/>
4、获取MongoDatabase对象
public static MongoDatabase GetMongoDatabase()
{
MongoClient mongoClient = new MongoClient(ConfigurationManager.AppSettings["MongoConn"]);
MongoServer mongoServer = mongoClient.GetServer();
return mongoServer.GetDatabase(ConfigurationManager.AppSettings["Database"]);
}
5、新建Model对象
可以指定,表中的实际字段名称
[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对象
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、根据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、更新数据
可以使用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);
}