1、安装包 MongoDB.Driver

2、定义顶层类

///

/// monggodb规范
///

public abstract class MongoDBToolBase
{
///

/// 客户端
///

protected MongoClient mongoClient { get; private set; }
///

/// 数据库
///

protected IMongoDatabase? database;

///

/// 构造
///

///
protected MongoDBToolBase(string conn) {
this.mongoClient = new MongoClient(conn);
}
}

3、定义操作类

///

/// MongoDB 操作类
///

public class MongoDBTool : MongoDBToolBase where T : class
{
///

/// 构造
///

public MongoDBTool(string conn) : base(conn)
{
List attributes
= typeof(T).GetAttribute().FindAttributeEntity();

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

///

/// 得到值
/// 一个条件
///

/// 表名
/// 列名
/// 值
///
public string GetOneCol(string collection, string colName, string value)
{
return this.database?
.GetCollection(collection)
.Find(Builders.Filter.Eq(colName, value))
.ToEnumerable()
.FirstOrDefault()?
.ToJson()
?? string.Empty;
}
}

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

///

/// MongoDB数据库名称
///

public class MongoDBDatabase : Attribute
{
///

/// 名称
///

public string name { get; set; }

///

/// 构造
///

///
public MongoDBDatabase(string name)
{
this.name = name;
}
}

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

///

/// 测试表
///

[MongoDBDatabase(“test”)]
public class MongodbTestModel
{
///

/// mongoid
///

public ObjectId _id { get; set; }
///

/// 名称
///

public string name { get; set; } = string.Empty;
///

/// 密码
///

public string password { get; set; } = string.Empty;
///

/// 备注
///

public string rem { get; set; } = string.Empty;
}

6、ioc注入

//注入mongodb单实例
builder.Services.AddSingleton(new MongoDBTool(builder.Configuration.GetValue(“mongodb”)));

7、配置文件

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

8、扩展的注解工具类

///

/// 注解工具
///

public static class AttributeTool
{
///

/// 获取注解
///

///
///
public static List GetAttribute(this Type cls)
{
// 获取所有自定义特性(包括注解)
return cls.GetCustomAttributes().ToList();
}

///

/// 看看是否存在有对应注解实体
/// 存在则返回
///

/// 返回对应的实体数据
///
///
public static List FindAttributeEntity(this List attributes)
{
List temp = new List();

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

if (attribute?.IsDefaultAttribute() ?? true)
{
return temp;
}

temp.Add(attribute);

return temp;
}
}

9、接口

///

/// 查询
///

///
[HttpPost(“search/{name}”)]
public string SearchData([FromServices] MongoDBTool mongoDBTool, string name)
{
return mongoDBTool.GetOneCol(“test”, “name”, name);
}

都这样了还有什么好说的

附加操作

/// /// 插入一条数据/// public void InsertOne(T mongodb){List attributes= typeof(T).GetAttribute().FindAttributeEntity();if (!attributes.Any()){return;}this.database?.GetCollection(((MongoDBCollection)attributes.First()).name).InsertOne(mongodb.ToBsonDocument());}/// /// 插入多条数据/// public void InsertMul(List mongodb){List attributes= typeof(T).GetAttribute().FindAttributeEntity();List collection = new List();if (!attributes.Any()){return;}mongodb.ForEach(mo =>{collection.Add(mo.ToBsonDocument());});this.database?.GetCollection(((MongoDBCollection)attributes.First()).name).InsertMany(collection);}/// /// 得到值/// 一个条件/// /// 表名/// 列名/// 值/// public string GetOneCol(string collection, string colName, string value){return this.database?.GetCollection(collection).Find(Builders.Filter.Eq(colName, value)).ToEnumerable().FirstOrDefault()?.ToJson()?? string.Empty;}/// /// 得到值/// 多个条件/// /// 表名/// 列名/// 值/// public string GetOneMul(string collection, string colName, string value){FilterDefinition filter = Builders.Filter.And(Builders.Filter.Eq("password", "77"),Builders.Filter.Or(Builders.Filter.Eq(colName, value), Builders.Filter.Eq(colName, "几个")));List? list = this.database?.GetCollection(collection).Find(filter).ToList();return list?.ToJson() ?? string.Empty;}