Asp.net Core 项目中如何使用 MongoDB 数据库

时间:2024-01-15 17:52:56

内容来源 https://blog.csdn.net/qq_26900081/article/details/83272132

一、添加依赖

1、MongoDB.Driver

2、MongoDB.Bson

Asp.net Core 项目中如何使用 MongoDB 数据库

二、配置服务到StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
  //添加mongodb依赖
  string mongoConnectionString = Configuration.GetSection("Mongo:ConnectionString").Value;
  services.AddSingleton(new MongoClient(mongoConnectionString));
}

三、添加配置到appsettings.json

{
  "Mongo": {
    "ConnectionString": "mongodb://账号:密码@服务器IP:27017/默认数据库名称"
  }
}

四、自己编写的一个帮助类;这里只公布一部分。 其余的可以自行拓展

public class MongoBase<T>: IMongoBase<T> //接口可自己根据此类抽象出来
{   private IMongoCollection<T> mongoClient;
  /// <summary>
  ///
  /// </summary>
  /// <param name="client"></param>
  /// <param name="name">MongoDB的表名</param>
  public MongoBase(MongoClient client, string name)
  {
    var database = client.GetDatabase("数据库名称");
    mongoClient = database.GetCollection<T>(name);
  }   #region 新增单个 + void InsertOne(T entity)
  /// <summary>
  /// 新增单个
  /// </summary>
  /// <param name="entity"></param>
  public void InsertOne(T entity)
  {
    mongoClient.InsertOne(entity);
  }
  #endregion   #region 批量新增 + void InsertMany(IEnumerable<T> entity)
  /// <summary>
  /// 批量新增
  /// </summary>
  /// <param name="entity"></param>
  public void InsertMany(IEnumerable<T> entity)
  {
    mongoClient.InsertMany(entity);
  }
  #endregion   #region 查找第一个 + T FindFirst(FilterDefinition<T> filter,FindOptions option = null)
  /// <summary>
  /// 查找第一个
  /// </summary>
  /// <param name="filter"></param>
  /// <param name="option"></param>
  /// <returns></returns>
  public T FindFirst(FilterDefinition<T> filter, FindOptions option = null)
  {
    return mongoClient.Find(filter, option).FirstOrDefault();
  }
  #endregion   #region 查找多个 + List<T> FindList(FilterDefinition<T> filter, FindOptions option = null)
  /// <summary>
  /// 查找多个
  /// </summary>
  /// <param name="filter"></param>
  /// <param name="option"></param>
  /// <returns></returns>
  public List<T> FindList(FilterDefinition<T> filter, FindOptions option = null)
  {
    return mongoClient.Find(filter, option).ToList();
  }
  #endregion }

五、编写一个MongoDB集合 

这里使用一个叫UserInfo的MongoDB数据库集合做测试

public class UserInfoService : MongoBase<UserInfo>
{
  public UserInfoService(MongoClient client) : base(client, "UserInfo")
  { } }

六、在Controller中使用

public class MongoController : Controller
{
  private UserInfoService userInfo;
//使用DI注入;
  public MongoController(UserInfoService _userInfo)
  {
    this.userInfo = _userInfo;
  }
  public IActionResult Index()
  {
    UserInfo user = userInfo.FindFirst(Builders<UserInfo>.Filter.Eq(p => p.Name, "Test"));
    userInfo.InsertOne(new UserInfo() { Name="Test", UserID= });     user = userInfo.FindFirst(Builders<UserInfo>.Filter.Eq(p => p.Name, "Test"));
    return View();
  }
}