第二节:基于.Net 连接Mongodb基础操作CRUD实战

一. 实操

(详见官网:https://www.mongodb.com/zh-cn/docs/drivers/csharp/current/quick-start/)

1. 相关程序集

  【MongoDB.Driver 2.29.0

    相关实体:加上如下特性,id值自动生成。

 public class ShipInfo
    {
        /// <summary>
        /// 自动生成id
        /// </summary>
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string id { set; get; }
        public string shipCode { set; get; }   
        public string shipName { set; get; }       
        public decimal shipPrice { set; get; }    
        public DateTime addTime { set; get; }     
        public int delflag { set; get; } 

    }

2. 建立连接

   对于db和collection,有的话直接连接,没有则创建,但必须进行相应的数据操作的时候才会创建。

public class HomeController : ControllerBase
{
        private readonly IMongoCollection<ShipInfo> shipService;
        public HomeController()
        {
             var settings = new MongoClientSettings
              {
                  Server = new MongoServerAddress("47.xx.xx.xx", 27017),
                  //对应的数据库、账号、密码 (这里的ship1账号仅有ShipDB1的权限)
                  //Credential = MongoCredential.CreateCredential("ShipDB1", "ship1", "123456")
                  //适用于所有数据,数据位置需要写admin
                  Credential = MongoCredential.CreateCredential("admin", "ypf", "123456")
              };

              // 创建MongoClient对象
              var client = new MongoClient(settings);
              // 2. 获取数据库ShipDB 【若没有,则自动创建,插入数据的时候才生效】
              var database = client.GetDatabase("ShipDB1");
              // 3. 获取表 ShipInfo【若没有,则自动创建,插入数据的时候才生效】
              shipService = database.GetCollection<ShipInfo>("ShipInfo");
        }
  }

 

3. 增加

单条:InsertOne

 /// <summary>
        /// 插入-单条
        /// </summary>
        [HttpPost]
        public string InsertOne()
        {
            ShipInfo shipInfo = new()
            {
                shipName = "001",
                shipCode = "test1",
                shipPrice = 1000,
                addTime = DateTime.Now,
                delflag = 0
            };
            shipService.InsertOne(shipInfo);
            return "okok";
        }

多条:InsertMany

  /// <summary>
        /// 插入-多条
        /// </summary>
        [HttpPost]
        public string InsertMany()
        {
            List<ShipInfo> shipList = new List<ShipInfo>();
            for (int i = 1; i <= 5; i++)
            {
                ShipInfo shipInfo = new();
                shipInfo.shipName = "ypf-" + i;
                shipInfo.shipCode = "000-" + i;
                shipInfo.shipPrice = 1000;
                shipInfo.addTime = DateTime.Now.AddDays(i);
                shipInfo.delflag = 0;
                shipList.Add(shipInfo);
            }
            shipService.InsertMany(shipList);
            return "ok";
        }

如下图:

 

4. 删除

单条:DeleteOne

        /// <summary>
        /// 删除-单条
        /// </summary>
        [HttpPost]
        public string DeleteOne(string id)
        {
            DeleteResult result = shipService.DeleteOne<ShipInfo>(u => u.id == id);
            return "删除成功--条数为:" + result.DeletedCount;
        }

多条:DeleteMany

    /// <summary>
    /// 删除-多条条
    /// </summary>
    [HttpPost]
    public string DeleteMany(string shipName)
    {
        DeleteResult result = shipService.DeleteMany(u => u.shipName.Contains(shipName));
        return "删除成功--条数为:" + result.DeletedCount;
    }

 

5. 修改

单条: UpdateOne

    /// <summary>
    /// 更新-单条 (根据id值更新)
    /// </summary>
    /// <param name="id">编号</param>
    /// <param name="shipName">船名</param>
    /// <param name="shipCode">船编码</param>
    /// <returns></returns>
    [HttpGet]
    public string UpdateOne(string id, string shipName, string shipCode)
    {
        var myUpdate = Builders<ShipInfo>.Update
                       .Set("shipName", shipName)
                       .Set("shipCode", shipCode);

        UpdateResult result = shipService.UpdateOne(u => u.id == id, myUpdate);
        return "更新成功--条数为:" + result.ModifiedCount;
    }

多条: UpdateMany

    /// <summary>
    /// 批量更新-多条 (根据shipName值更新)
    /// </summary>
    /// <param name="shipName">船名</param>
    /// <param name="shipCode">船编码</param>
    [HttpGet]
    public string UpdateMany(string shipName, string shipCode)
    {
        var myUpdate = Builders<ShipInfo>.Update
                       .Set("shipCode", shipCode);
        UpdateResult result = shipService.UpdateMany(u => u.shipName.Contains(shipName), myUpdate);
        return "更新成功--条数为:" + result.ModifiedCount;
    }

 

6. 查询

查询:Find

    /// <summary>
    /// 条件查询
    /// (根据船名查询信息)
    /// </summary>
    /// <param name="shipName">船名</param>
    /// <returns></returns>
    [HttpPost]
    public List<ShipInfo> GetByShipName(string shipName)
    {
        return shipService.Find(u => u.shipName.Contains(shipName)).ToList();
    }

分页:Skip+Limit

    /// <summary>
    /// 06-分页查询
    /// </summary>
    /// <param name="pageIndex">当前页码</param>
    /// <param name="pageSize">每页数量</param>
    /// <returns></returns>
    [HttpGet]
    public List<ShipInfo> GetPageList(int pageIndex = 1, int pageSize = 1)
    {
        return shipService.Find(u => true).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();
    }

排序:SortBy、SortByDescending

   /// <summary>
   /// 排序(根据时间字段)
   /// </summary>
   /// <param name="isAsc">是否升序</param>
   /// <returns></returns>
   [HttpPost]
   public List<ShipInfo> GetListBySort(bool isAsc = true)
   {
       if (isAsc)
       {
           return shipService.Find(u => true).SortBy(u => u.addTime).ToList();
       }
       else
       {
           return shipService.Find(u => true).SortByDescending(u => u.addTime).ToList();
       }
   }

 

7. 创建索引

索引:CreateOne+CreateIndexModel


        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="indexName">索引名称</param>
        /// <returns></returns>
        [HttpPost]
        public string CreateOne(string indexName)
        {
            var indexKeysDefinition = Builders<ShipInfo>.IndexKeys.Ascending(indexName);
            shipService.Indexes.CreateOne(new CreateIndexModel<ShipInfo>(indexKeysDefinition));

            return "ok";
        }

如下图:

 

 

 

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 
posted @ 2024-10-08 20:02  Yaopengfei  阅读(33)  评论(1编辑  收藏  举报