无为清净楼资源网 Design By www.qnjia.com

以前项目基本上全部使用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"htmlcode">
[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 多条件查询的资料请关注其它相关文章!

标签:
.net,core,MongoDB,net,core,MongoDB,多条件查询,MongoDB,多条件查询

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。