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://www.toymoban.com/news/detail-817800.html
附加操作文章来源地址https://www.toymoban.com/news/detail-817800.html
/// <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;
}
到了这里,关于.net core 6 集成和使用 mongodb的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!