.net core 6 集成和使用 mongodb

news/2024/5/19 20:57:13 标签: .netcore, mongodb, 数据库

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);
}

都这样了还有什么好说的

附加操作

/// <summary>
/// 插入一条数据
/// </summary>
public void InsertOne(T mongodb)
{
    List<Attribute> attributes
        = typeof(T).GetAttribute().FindAttributeEntity<MongoDBCollection>();

    if (!attributes.Any())
    {
        return;
    }

    this.database?
        .GetCollection<BsonDocument>(((MongoDBCollection)attributes.First()).name)
        .InsertOne(mongodb.ToBsonDocument());
}

/// <summary>
/// 插入多条数据
/// </summary>
public void InsertMul(List<T> mongodb)
{
    List<Attribute> attributes
        = typeof(T).GetAttribute().FindAttributeEntity<MongoDBCollection>();
    List<BsonDocument> collection = new List<BsonDocument>();

    if (!attributes.Any())
    {
        return;
    }

    mongodb.ForEach(mo =>
    {
        collection.Add(mo.ToBsonDocument());
    });

    this.database?
        .GetCollection<BsonDocument>(((MongoDBCollection)attributes.First()).name)
        .InsertMany(collection);
}


http://www.niftyadmin.cn/n/5318676.html

相关文章

nginx基础面试题以及配置文件解析和命令控制

目录 1、nginx是什么 2、nginx的特点 3、为什么中国大陆有&#xff1a;百度、京东、新浪、网易、腾讯、淘宝等这么多用户使用nginx 4、nginx 的内部技术架构 上一期我们配置安装了nginx接着讲一下nginx配置文件的解析和nginx 命令控制 感谢观看&#xff01;希望能够帮助到…

GBASE南大通用GBase 8a ODBC 配置SSL

GBase南大通用 GBase 8a MPP Cluster支持SSL标准协议&#xff0c;SSL协议是一种安全性更高的协议标准&#xff0c;它加入了数字签名和数字证书来实现客户端和服务器的双向身份验证&#xff0c;保证了通信双方更加安全的数据传输。 GBase南大通用 GBase 8a 通过SSL加密应用端OD…

K8s---存储卷(动态pv和pvc)

当我要发布pvc可以生成pv&#xff0c;还可以共享服务器上直接生成挂载目录。pvc直接绑定pv。 动态pv需要两个组件 1、卷插件&#xff1a;k8s本生支持的动态pv创建不包括nfs&#xff0c;需要声明和安装一个外部插件 Provisioner: 存储分配器。动态创建pv,然后根据pvc的请求自动…

NumPy 2 要来了,一定记得这样做!

你好&#xff0c;我是坚持分享干货的 EarlGrey&#xff0c;翻译出版过《Python编程无师自通》、《Python并行计算手册》等技术书籍。 如果我的分享对你有帮助&#xff0c;请关注我&#xff0c;一起向上进击。 NumPy 的下一个大版本 NumPy 2&#xff0c;就快要来了&#xff01; …

面试150-56(Leetcode150逆波兰表达式求值)

代码&#xff1a; class Solution {public int evalRPN(String[] tokens) {Deque<Integer> stack new LinkedList<>();int n tokens.length;for(int i0;i<n;i){String token tokens[i];if(isNumber(token)){stack.push(Integer.parseInt(token));}else{int …

点灯大师的第一步 -imx6ull

实验目的 编写linux 的驱动程序&#xff0c;并移植到IMX6ULL -MINI开发板上&#xff0c;实现将 LED灯点亮&#xff0c;并周期性闪烁&#xff0c;周期间隔可调节的功能。出现的问题 2.1 点灯 2.1.1 设备加入到设备树中 设置pin 功能与 GPIO功能 PIN功能(PAD功能)又分为电气特性(…

OpenGL和OpenGL ES显示YUV图片的着色器差别(一)

这里解释的只是用于显示YUV图片的代码&#xff0c;没有增加任何效果&#xff1a; OpenGL 的片段着色器片段&#xff1a; const char *fsrc "varying vec2 textureOut; \uniform sampler2D tex_y; \uniform sampler2D tex_u; \uniform sampler2D tex_v; \void main(void…

【自控实验】2. 采样控制系统特性

本科课程实验报告&#xff0c;有太多公式和图片了&#xff0c;干脆直接转成图片了 仅分享和记录&#xff0c;不保证全对 通过对二阶连续系统、二阶采样系统和具有保持器的二阶采样系统仿真实验&#xff0c;比较三种系统的特性&#xff0c;加深对采样控制系统的了解 使用matl…