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);
}/// <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;
}/// <summary>
/// 得到值
/// 多个条件
/// </summary>
/// <param name="collection">表名</param>
/// <param name="colName">列名</param>
/// <param name="value">值</param>
/// <returns></returns>
public string GetOneMul(string collection, string colName, string value)
{FilterDefinition<T> filter = Builders<T>.Filter.And(Builders<T>.Filter.Eq("password", "77"),Builders<T>.Filter.Or(Builders<T>.Filter.Eq(colName, value), Builders<T>.Filter.Eq(colName, "几个")));List<T>? list = this.database?.GetCollection<T>(collection).Find<T>(filter).ToList();return list?.ToJson() ?? string.Empty;
}