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


本文摘自PHP中文网,作者coldplay.xixi,侵删。

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

相关学习推荐:C#.Net开发图文教程

一、准备工作

1. 安装过程, 不赘述了

2. 添加ReferencePackage

1

2

dotnet add package mongodb.bson

dotnet add package mongodb.driver

3. appsetting.json添加连接配置

1

2

3

4

5

"MongodbHost": {

  "Connection": "mongodb://[username]:[password]@[ip]:[port]",

  "DataBase": "[database]",

  "Table": ""

 },

4. 获取MongoDBConfig 的方法

1

2

3

4

5

6

7

8

9

10

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类的属性.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

#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

三、调用查询方法

阅读剩余部分

相关阅读 >>

httpclient向https发送数据建立ssl连接时的异常

.net mymvc框架处理返回值的教程

关于c#如何实现的udp收发请求工具类的示例代码分析

asp.net core如何安装?详解asp.net core安装的实例教程

asp.net core中新功能--环境变量和启动设置

c#编写windows服务程序的图文详解

c# 加密类工具实例分析

c# 多线程--线程池的详细介绍

解决 asp.net core mysql varchar 字符串截取实例教程

c#实现添加word文本与图片超链接的方法

更多相关阅读请进入《.net》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...