欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net Core如何对MongoDB执行多条件查询

程序员文章站 2022-03-08 08:11:19
以前项目基本上全部使用mysql数据库, 最近项目排期空出了一点时间leader决定把日志模块迁移到插入/查询性能更好的mongodb上. 多条件查询的写法着实费了些功夫, 撰文记录一下.一、准备工作...

以前项目基本上全部使用mysql数据库, 最近项目排期空出了一点时间leader决定把日志模块迁移到插入/查询性能更好的mongodb上. 多条件查询的写法着实费了些功夫, 撰文记录一下.

一、准备工作

1. 安装过程, 不赘述了

2. 添加referencepackage

dotnet add package mongodb.bson
dotnet add package mongodb.driver

3. appsetting.json添加连接配置

"mongodbhost": {
  "connection": "mongodb://[username]:[password]@[ip]:[port]",
  "database": "[database]",
  "table": ""
 },

4. 获取mongodbconfig 的方法

public static mongodbhostoptions mongodbconfig()
{
  var builder = new configurationbuilder()
        .setbasepath(directory.getcurrentdirectory())
        .addjsonfile("appsettings.json");

  iconfiguration configuration = builder.build();
  var option = configuration.getsection("mongodbhost");
  return new mongodbhostoptions { connection = option["connection"], database = option["database"], table = option["table"] };
}

二、查询方法

这里的查询方法是网上找的, 直接拿来用了. 如果是单一数据源的话, 这里的host可以提取出来成为helper类的属性.

#region findlistbypage 分页查询集合
  /// <summary>
  /// 分页查询集合
  /// </summary>
  /// <param name="filter">查询条件</param>
  /// <param name="pageindex">当前页</param>
  /// <param name="pagesize">页容量</param>
  /// <param name="count">总条数</param>
  /// <param name="field">要查询的字段,不写时查询全部</param>
  /// <param name="sort">要排序的字段</param>
  /// <returns></returns>
  public static list<t> findlistbypage(filterdefinition<t> filter, int pageindex, int pagesize, out int count, string[] field = null, sortdefinition<t> sort = null)
  {
    try
    {
      mongodbhostoptions host = tools.appsettingstools.mongodbconfig();
      host.table = "wsmessagelog";
      var client = mongodbclient<t>.mongodbinfoclient(host);
      count = convert.toint32(client.countdocuments(filter));
      //不指定查询字段
      if (field == null || field.length == 0)
      {
        if (sort == null) return client.find(filter).skip((pageindex - 1) * pagesize).limit(pagesize).tolist();
        //进行排序
        return client.find(filter).sort(sort).skip((pageindex - 1) * pagesize).limit(pagesize).tolist();
      }

      //指定查询字段
      var fieldlist = new list<projectiondefinition<t>>();
      for (int i = 0; i < field.length; i++)
      {
        fieldlist.add(builders<t>.projection.include(field[i].tostring()));
      }
      var projection = builders<t>.projection.combine(fieldlist);
      fieldlist?.clear();

      //不排序
      if (sort == null) return client.find(filter).project<t>(projection).skip((pageindex - 1) * pagesize).limit(pagesize).tolist();

      //排序查询
      return client.find(filter).sort(sort).project<t>(projection).skip((pageindex - 1) * pagesize).limit(pagesize).tolist();

    }
    catch (exception ex)
  {
    throw ex;
  }
}
#endregion

三、调用查询方法

这里还踩了一个坑. mongodb里存储的时间是格林尼治时间, 插入8:00, 查询时会发现变成了0:00,所以定义时间属性的时候需要加个标签

[bsondatetimeoptions(kind = datetimekind.local)]
public datetime logtime { get; set; }

这里的oprlogmodel是定义了查询条件的类.

public static logpager<log_operate> get_operate_log_mongo(oprlogmodel qmodel)
{
  logpager<log_operate> pager = new logpager<log_operate>();
  filterdefinition<log_operate> filters;

   var sortbuilder = builders<log_operate>.sort;
  var sort = sortbuilder.descending("operate_time");

  #region 用户权限过滤
  ienumerable<string> idlist = dev_devicerepository.getbinding(qmodel.user_id);
   filters = builders<log_operate>.filter.in("device_id", idlist);
  #endregion

  if (!string.isnullorempty(qmodel.device_id))
  {
    var filters_did = builders<log_operate>.filter.eq("device_id", qmodel.device_id);
    filters = builders<log_operate>.filter.and(filters, filters_did);
  }
  if (qmodel.sdate != null)
  {
    var filters_sdate = builders<log_operate>.filter.gte<datetime>("operate_time", convert.todatetime(qmodel.sdate));
    filters = builders<log_operate>.filter.and(filters, filters_sdate);
  }
  if (qmodel.edate != null)
  {
    var filters_edate = builders<log_operate>.filter.lte<datetime>("operate_time", convert.todatetime(qmodel.edate));
    filters = builders<log_operate>.filter.and(filters, filters_edate);
  }
  int total;
  pager.data = mongotools<log_operate>.findlistbypage(filters, qmodel.pageindex, (qmodel.pageindex - 1) * qmodel.pagesize, out total, null, sort);
  pager.total = total;
  return pager;
}
#endregion

也可以先定义一个空的filterdefinition, 然后与各查询条件通过and聚合:

filterdefinition<log_operate> filters = filterdefinition<log_operate>.empty;
var filters_idlist = builders<log_operate>.filter.in("device_id", idlist);
filters = builders<log_operate>.filter.and(filters, filters_idlist);

以上就是.net core如何对mongodb执行多条件查询的详细内容,更多关于.net core对mongodb 多条件查询的资料请关注其它相关文章!