C# 使用mongodb 帮助类
在C#中使用MongoDB,你需要安装MongoDB的C#驱动程序,通常使用MongoDB.Driver。
以下是一个简单的帮助类,用于连接MongoDB数据库并执行基本的CRUD操作。
首先,通过NuGet安装MongoDB.Driver:
Install-Package MongoDB.Driver
using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq.Expressions; public static class MongoDBHelper<T> where T : class { private static IMongoCollection<T> _collection; static MongoDBHelper() { var connectionString = "your_mongodb_connection_string"; var client = new MongoClient(connectionString); var database = client.GetDatabase("your_database_name"); _collection = database.GetCollection<T>("your_collection_name"); } public static List<T> GetAll() { return _collection.Find(new BsonDocument()).ToList(); } public static T GetById(string id) { return _collection.Find(Builders<T>.Filter.Eq("_id", id)).FirstOrDefault(); } public static T GetSingle(Expression<Func<T, bool>> predicate) { return _collection.Find(predicate).FirstOrDefault(); } public static void Insert(T entity) { _collection.InsertOne(entity); } public static void Update(T entity) { _collection.ReplaceOne(Builders<T>.Filter.Eq("_id", entity.Id), entity); } public static void Delete(string id) { _collection.DeleteOne(Builders<T>.Filter.Eq("_id", id)); } }
使用该帮助类
public class MyEntity { public string Id { get; set; } public string Name { get; set; } } // 获取所有记录 List<MyEntity> entities = MongoDBHelper<MyEntity>.GetAll(); // 通过ID获取单个记录 MyEntity entity = MongoDBHelper<MyEntity>.GetById("some_id"); // 插入新记录 MyEntity newEntity = new MyEntity { Name = "New Entity" }; MongoDBHelper<MyEntity>.Insert(newEntity); // 更新记录 newEntity.Name = "Updated Name"; MongoDBHelper<MyEntity>.Update(newEntity); // 删除记录 MongoDBHelper<MyEntity>.Delete("some_id");
如有疑问或者错误的地方,请跟帖,本人会第一时间答复以及相互学习,谢谢!个人会不断的上传自己的学习心得!
好了今天就先到这里,下次有时间再更新,如果存在不合理的地方,欢迎大家多多指教留言!!!
分类:
NOSQL/MongoDB
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
2019-11-06 Layer.js弹层的一些简单的使用
2019-11-06 Sqlserver表值函数来获取逗号分隔的ID