.net core 6 集成和使用 mongodb

发布时间:2024年01月11日

1、安装包 MongoDB.Driver

2、定义顶层类

/// <summary>
/// monggodb规范
/// </summary>
public abstract class MongoDBToolBase
{
??? /// <summary>
??? /// 客户端
??? /// </summary>
??? protected MongoClient mongoClient { get; private set; }
??? /// <summary>
??? /// 数据库
??? /// </summary>
??? protected IMongoDatabase? database;

??? /// <summary>
??? /// 构造
??? /// </summary>
??? /// <param name="conn"></param>
??? protected MongoDBToolBase(string conn) {
??????? this.mongoClient = new MongoClient(conn);
??? }
}

3、定义操作类

/// <summary>
/// MongoDB 操作类
/// </summary>
public class MongoDBTool<T> : MongoDBToolBase where T : class
{
??? /// <summary>
??? /// 构造
??? /// </summary>
??? public MongoDBTool(string conn) : base(conn)
??? {
??????? List<Attribute> attributes
??????????? = typeof(T).GetAttribute().FindAttributeEntity<MongoDBDatabase>();

??????? if (attributes.Any())
??????? {
??????????? this.database = this.mongoClient.GetDatabase(((MongoDBDatabase)attributes.First()).name);
??????? }
??????? else
??????? {
??????????? throw new Exception("未找到MongoDBDatabase注解");
??????? }
??? }

??? /// <summary>
??? /// 得到值
??? /// 一个条件
??? /// </summary>
??? /// <param name="collection">表名</param>
??? /// <param name="colName">列名</param>
??? /// <param name="value">值</param>
??? /// <returns></returns>
??? public string GetOneCol(string collection, string colName, string value)
??? {
??????? return this.database?
??????????? .GetCollection<T>(collection)
??????????? .Find<T>(Builders<T>.Filter.Eq(colName, value))
??????????? .ToEnumerable<T>()
??????????? .FirstOrDefault()?
??????????? .ToJson()
??????????? ?? string.Empty;
??? }
}

4、定义一个注解,映射mongodb的数据库名称

/// <summary>
/// MongoDB数据库名称
/// </summary>
public class MongoDBDatabase : Attribute
{
??? /// <summary>
??? /// 名称
??? /// </summary>
??? public string name { get; set; }

??? /// <summary>
??? /// 构造
??? /// </summary>
??? /// <param name="name"></param>
??? public MongoDBDatabase(string name)
??? {
??????? this.name = name;
??? }
}

5、定义一个实体,映射数据库表字段并且关联对应的数据库

/// <summary>
/// 测试表
/// </summary>
[MongoDBDatabase("test")]
public class MongodbTestModel
{
??? /// <summary>
??? /// mongoid
??? /// </summary>
??? public ObjectId _id { get; set; }
??? /// <summary>
??? /// 名称
??? /// </summary>
??? public string name { get; set; } = string.Empty;
??? /// <summary>
??? /// 密码
??? /// </summary>
??? public string password { get; set; } = string.Empty;
??? /// <summary>
??? /// 备注
??? /// </summary>
??? public string rem {? get; set; } = string.Empty;
}

6、ioc注入

//注入mongodb单实例
builder.Services.AddSingleton(new MongoDBTool<MongodbTestModel>(builder.Configuration.GetValue<string>("mongodb")));

7、配置文件

"mongodb": "mongodb://username:password@localhost:27017/?authSource=admin"

8、扩展的注解工具类

/// <summary>
/// 注解工具
/// </summary>
public static class AttributeTool
{
??? /// <summary>
??? /// 获取注解
??? /// </summary>
??? /// <param name="cls"></param>
??? /// <returns></returns>
??? public static List<Attribute> GetAttribute(this Type cls)
??? {
??????? // 获取所有自定义特性(包括注解)
??????? return cls.GetCustomAttributes().ToList();
??? }

??? /// <summary>
??? /// 看看是否存在有对应注解实体
??? /// 存在则返回
??? /// </summary>
??? /// <typeparam name="T">返回对应的实体数据</typeparam>
??? /// <param name="attributes"></param>
??? /// <returns></returns>
??? public static List<Attribute> FindAttributeEntity<T>(this List<Attribute> attributes)
??? {
??????? List<Attribute> temp = new List<Attribute>();

??????? Attribute? attribute = attributes.FirstOrDefault(attr =>
??????? {
??????????? return attr.GetType() == typeof(T);
??????? });
?????? ?
??????? if (attribute?.IsDefaultAttribute() ?? true)
??????? {
??????????? return temp;
??????? }

??????? temp.Add(attribute);
?????? ?
??????? return temp;
??? }
}

9、接口

/// <summary>
/// 查询
/// </summary>
/// <returns></returns>
[HttpPost("search/{name}")]
public string SearchData([FromServices] MongoDBTool<MongodbTestModel> mongoDBTool, string name)
{
??? return mongoDBTool.GetOneCol("test", "name", name);
}

都这样了还有什么好说的

文章来源:https://blog.csdn.net/qq_40934195/article/details/135532116
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。