当前位置: 首页 > news >正文

企业建站团队泉州seo网络优化公司

企业建站团队,泉州seo网络优化公司,海南注册公司在哪个网站,青岛人力资源招聘官网用好数据映射#xff0c;MongoDB via Dotnet Core开发变会成一件超级快乐的事。一、前言MongoDB这几年已经成为NoSQL的头部数据库。由于MongoDB free schema的特性#xff0c;使得它在互联网应用方面优于常规数据库#xff0c;成为了相当一部分大厂的主数据选择#xff1b;… 用好数据映射MongoDB via Dotnet Core开发变会成一件超级快乐的事。 一、前言MongoDB这几年已经成为NoSQL的头部数据库。由于MongoDB free schema的特性使得它在互联网应用方面优于常规数据库成为了相当一部分大厂的主数据选择而它的快速布署和开发简单的特点也吸引着大量小开发团队的支持。关于MongoDB快速布署我在15分钟从零开始搭建支持10w用户的生产环境(二)里有写需要了可以去看看。 作为一个数据库基本的操作就是CRUD。MongoDB的CRUD不使用SQL来写而是提供了更简单的方式。方式一、BsonDocument方式BsonDocument方式适合能熟练使用MongoDB Shell的开发者。MongoDB Driver提供了完全覆盖Shell命令的各种方式来处理用户的CRUD操作。这种方法自由度很高可以在不需要知道完整数据集结构的情况下完成数据库的CRUD操作。方式二、数据映射方式数据映射是最常用的一种方式。准备好需要处理的数据类直接把数据类映射到MongoDB并对数据集进行CRUD操作。 下面对数据映射的各个部分我会逐个说明。二、开发环境基础工程这个Demo的开发环境是Mac VS Code Dotnet Core 3.1.2。建立工程% dotnet new sln -o demo The template Solution File was created successfully. % cd demo  % dotnet new console -o demo The template Console Application was created successfully.Processing post-creation actions... Running dotnet restore on demo/demo.csproj...Determining projects to restore...Restored demo/demo/demo.csproj (in 162 ms).Restore succeeded. % dotnet sln add demo/demo.csproj  Project demo/demo.csproj added to the solution. 建立工程完成。下面增加包mongodb.driver到工程% cd demo % dotnet add package mongodb.driverDetermining projects to restore... info : Adding PackageReference for package mongodb.driver into project demo/demo/demo.csproj. info : Committing restore... info : Writing assets file to disk. Path: demo/demo/obj/project.assets.json log  : Restored /demo/demo/demo.csproj (in 6.01 sec). 项目准备完成。看一下目录结构% tree . . ├── demo │   ├── Program.cs │   ├── demo.csproj │   └── obj │       ├── demo.csproj.nuget.dgspec.json │       ├── demo.csproj.nuget.g.props │       ├── demo.csproj.nuget.g.targets │       ├── project.assets.json │       └── project.nuget.cache └── demo.slnmongodb.driver是MongoDB官方的数据库SDK从Nuget上安装即可。三、Demo准备工作创建数据映射的模型类CollectionModel.cs现在是个空类后面所有的数据映射相关内容会在这个类进行说明public class CollectionModel { } 并修改Program.cs准备Demo方法以及连接数据库:class Program {private const string MongoDBConnection  mongodb://localhost:27031/admin;private static IMongoClient _client  new MongoClient(MongoDBConnection);private static IMongoDatabase _database  _client.GetDatabase(Test);private static IMongoCollectionCollectionModel _collection  _database.GetCollectionCollectionModel(TestCollection);static async Task Main(string[] args){await Demo();Console.ReadKey();}private static async Task Demo(){} } 四、字段映射从上面的代码中我们看到在生成Collection对象时用到了CollectionModelIMongoDatabase _database  _client.GetDatabase(Test); IMongoCollectionCollectionModel _collection  _database.GetCollectionCollectionModel(TestCollection); 这两行其实就完成了一个映射的工作把MongoDB中Test数据库下TestCollection数据集就是SQL中的数据表映射到CollectionModel这个数据类中。换句话说就是用CollectionModel这个类来完成对数据集TestCollection的所有操作。 保持CollectionModel为空我们往数据库写入一行数据private static async Task Demo() {CollectionModel new_item  new CollectionModel();await _collection.InsertOneAsync(new_item); } 执行看一下写入的数据{ _id : ObjectId(5ef1d8325327fd4340425ac9) } OK我们已经写进去一条数据了。因为映射类是空的所以写入的数据也只有_id一行内容。 但是为什么会有一个_id呢1. ID字段MongoDB数据集中存放的数据称之为文档Document。每个文档在存放时都需要有一个ID而这个ID的名称固定叫_id。当我们建立映射时如果给出_id字段则MongoDB会采用这个ID做为这个文档的ID如果不给出MongoDB会自动添加一个_id字段。例如public class CollectionModel {public ObjectId _id { get; set; }public string title { get; set; }public string content { get; set; } } 和public class CollectionModel {public string title { get; set; }public string content { get; set; } } 在使用上是完全一样的。唯一的区别是如果映射类中不写_id则MongoDB自动添加_id时会用ObjectId作为这个字段的数据类型。ObjectId是一个全局唯一的数据。当然MongoDB允许使用其它类型的数据作为ID例如stringintlongGUID等但这就需要你自己去保证这些数据不超限并且唯一。例如我们可以写成public class CollectionModel {public long _id { get; set; }public string title { get; set; }public string content { get; set; } }我们也可以在类中修改_id名称为别的内容但需要加一个描述属性BsonIdpublic class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; } } 这儿特别要注意BsonId属性会告诉映射topic_id就是这个文档数据的ID。MongoDB在保存时会将这个topic_id转成_id保存到数据集中。在MongoDB数据集中ID字段的名称固定叫_id。为了代码的阅读方便可以在类中改为别的名称但这不会影响MongoDB中存放的ID名称。 修改Demo代码private static async Task Demo() {CollectionModel new_item  new CollectionModel(){title  Demo,content  Demo content,};await _collection.InsertOneAsync(new_item); } 跑一下Demo看看保存的结果{ _id : ObjectId(5ef1e1b1bc1e18086afe3183), title : Demo, content : Demo content } 2. 简单字段就是常规的数据字段直接写就成。public class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; }public int favor { get; set; } } 保存后的数据{ _id : ObjectId(5ef1e9caa9d16208de2962bb), title : Demo, content : Demo content, favor : NumberInt(100) } 3. 一个的特殊的类型 - Decimal说Decimal特殊是因为MongoDB在早期是不支持Decimal的。直到MongoDB v3.4开始数据库才正式支持Decimal。所以如果使用的是v3.4以后的版本可以直接使用而如果是以前的版本需要用以下的方式[BsonRepresentation(BsonType.Double, AllowTruncation  true)] public decimal price { get; set; } 其实就是把Decimal通过映射转为Double存储。4. 类字段把类作为一个数据集的一个字段。这是MongoDB作为文档NoSQL数据库的特色。这样可以很方便的把相关的数据组织到一条记录中方便展示时的查询。我们在项目中添加两个类Contact和Authorpublic class Contact {public string mobile { get; set; } } public class Author {public string name { get; set; }public ListContact contacts { get; set; } } 然后把Author加到CollectionModel中public class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; }public int favor { get; set; }public Author author { get; set; } } 嗯开始变得有点复杂了。完善Demo代码private static async Task Demo() {CollectionModel new_item  new CollectionModel(){title  Demo,content  Demo content,favor  100,author  new Author{name  WangPlus,contacts  new ListContact(),}};Contact contact_item1  new Contact(){mobile  13800000000,};Contact contact_item2  new Contact(){mobile  13811111111,};new_item.author.contacts.Add(contact_item1);new_item.author.contacts.Add(contact_item2);await _collection.InsertOneAsync(new_item); } 保存的数据是这样的{ _id : ObjectId(5ef1e635ce129908a22dfb5e), title : Demo, content : Demo content, favor : NumberInt(100),author : {name : WangPlus, contacts : [{mobile : 13800000000}, {mobile : 13811111111}]} } 这样的数据结构用着不要太爽5. 枚举字段枚举字段在使用时跟类字段相似。创建一个枚举TagEnumerationpublic enum TagEnumeration {CSharp  1,Python  2, } 加到CollectionModel中public class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; }public int favor { get; set; }public Author author { get; set; }public TagEnumeration tag { get; set; } } 修改Demo代码private static async Task Demo() {CollectionModel new_item  new CollectionModel(){title  Demo,content  Demo content,favor  100,author  new Author{name  WangPlus,contacts  new ListContact(),},tag  TagEnumeration.CSharp,};/* 后边代码略过 */ } 运行后看数据{ _id : ObjectId(5ef1eb87cbb6b109031fcc31), title : Demo, content : Demo content, favor : NumberInt(100), author : {name : WangPlus, contacts : [{mobile : 13800000000}, {mobile : 13811111111}]}, tag : NumberInt(1) } 在这里tag保存了枚举的值。我们也可以保存枚举的字符串。只要在CollectionModel中tag声明上加个属性public class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; }public int favor { get; set; }public Author author { get; set; }[BsonRepresentation(BsonType.String)]public TagEnumeration tag { get; set; } } 数据会变成{ _id : ObjectId(5ef1ec448f1d540919d15904), title : Demo, content : Demo content, favor : NumberInt(100), author : {name : WangPlus, contacts : [{mobile : 13800000000}, {mobile : 13811111111}]}, tag : CSharp } 6. 日期字段日期字段会稍微有点坑。这个坑其实并不源于MongoDB而是源于C#的DateTime类。我们知道时间根据时区不同时间也不同。而DateTime并不准确描述时区的时间。我们先在CollectionModel中增加一个时间字段public class CollectionModel {[BsonId]public ObjectId topic_id { get; set; }public string title { get; set; }public string content { get; set; }public int favor { get; set; }public Author author { get; set; }[BsonRepresentation(BsonType.String)]public TagEnumeration tag { get; set; }public DateTime post_time { get; set; } } 修改Demoprivate static async Task Demo() {CollectionModel new_item  new CollectionModel(){/* 前边代码略过 */post_time  DateTime.Now, /* 2020-06-23T20:12:40.4630000 */};/* 后边代码略过 */ } 运行看数据{ _id : ObjectId(5ef1f1b9a75023095e995d9f), title : Demo, content : Demo content, favor : NumberInt(100), author : {name : WangPlus, contacts : [{mobile : 13800000000}, {mobile : 13811111111}]}, tag : CSharp, post_time : ISODate(2020-06-23T12:12:40.4630000) } 对比代码时间和数据时间会发现这两个时间差了8小时 - 正好的中国的时区时间。 MongoDB规定在数据集中存储时间时只会保存UTC时间。如果只是保存像上边这样或者查询时使用时间作为条件例如查询post_time DateTime.Now的数据时是可以使用的不会出现问题。但是如果是查询结果中有时间字段那这个字段会被DateTime默认设置为DateTimeKind.Unspecified类型。而这个类型是无时区信息的输出显示时会造成混乱。为了避免这种情况在进行时间字段的映射时需要加上属性[BsonDateTimeOptions(Kind  DateTimeKind.Local)] public DateTime post_time { get; set; } 这样做会强制DateTime类型的字段为DateTimeKind.Local类型。这时候从显示到使用就正确了。 但是别高兴的太早这儿还有一个但是。这个但是是这样的数据集中存放的是UTC时间跟我们正常的时间有8小时时差如果我们需要按日统计比方每天的销售额/点击量怎么搞上面的方式解决不了。当然基于MongoDB自由的字段处理可以把需要统计的字段按年月日时分秒拆开存放像下面这样的class Post_Time {public int year { get; set; }public int month { get; set; }public int day { get; set; }public int hour { get; set; }public int minute { get; set; }public int second { get; set; } } 能解决但是Low哭了有没有 下面终极方案来了。它就是改写MongoDB中对于DateTime字段的序列化类。当当当先创建一个类MyDateTimeSerializerpublic class MyDateTimeSerializer : DateTimeSerializer {public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args){var obj  base.Deserialize(context, args);return new DateTime(obj.Ticks, DateTimeKind.Unspecified);}public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value){var utcValue  new DateTime(value.Ticks, DateTimeKind.Utc);base.Serialize(context, args, utcValue);} } 代码简单一看就懂。注意使用这个方法上边那个对于时间加的属性[BsonDateTimeOptions(Kind DateTimeKind.Local)]一定不要添加要不然就等着哭吧:P创建完了怎么用如果你只想对某个特定映射的特定字段使用比方只对CollectionModel的post_time字段来使用可以这么写[BsonSerializer(typeof(MyDateTimeSerializer))] public DateTime post_time { get; set; } 或者全局使用BsonSerializer.RegisterSerializer(typeof(DateTime), new MongoDBDateTimeSerializer()); BsonSerializer是MongoDB.Driver的全局对象。所以这个代码可以放到使用数据库前的任何地方。例如在Demo中我放在Main里了static async Task Main(string[] args) {BsonSerializer.RegisterSerializer(typeof(DateTime), new MyDateTimeSerializer());await Demo();Console.ReadKey(); } 这回看数据数据集中的post_time跟当前时间显示完全一样了你统计你分组可以随便霍霍了。7. Dictionary字段这个需求很奇怪。我们希望在一个Key-Value的文档中保存一个Key-Value的数据。但这个需求又是真实存在的比方保存一个用户的标签和标签对应的命中次数。数据声明很简单public Dictionarystring, int extra_info { get; set; } MongoDB定义了三种保存属性Document、ArrayOfDocuments、ArrayOfArrays默认是Document。属性写法是这样的[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionarystring, int extra_info { get; set; } 这三种属性下保存在数据集中的数据结构有区别。DictionaryRepresentation.Document{ extra_info : {type : NumberInt(1), mode : NumberInt(2)} } DictionaryRepresentation.ArrayOfDocuments{ extra_info : [{k : type, v : NumberInt(1)}, {k : mode, v : NumberInt(2)}] } DictionaryRepresentation.ArrayOfArrays{ extra_info : [[type, NumberInt(1)], [mode, NumberInt(2)]] } 这三种方式从数据保存上并没有什么区别但从查询来讲如果这个字段需要进行查询那三种方式区别很大。如果采用BsonDocument方式查询DictionaryRepresentation.Document无疑是写着最方便的。如果用Builder方式查询DictionaryRepresentation.ArrayOfDocuments是最容易写的。DictionaryRepresentation.ArrayOfArrays就算了。数组套数组查询条件写死人。我自己在使用时多数情况用DictionaryRepresentation.ArrayOfDocuments。五、其它映射属性上一章介绍了数据映射的完整内容。除了这些内容MongoDB还给出了一些映射属性供大家看心情使用。1. BsonElement属性这个属性是用来改数据集中的字段名称用的。看代码[BsonElement(pt)] public DateTime post_time { get; set; } 在不加BsonElement的情况下通过数据映射写到数据集中的文档字段名就是变量名上面这个例子字段名就是post_time。加上BsonElement后数据集中的字段名会变为pt。2. BsonDefaultValue属性看名称就知道这是用来设置字段的默认值的。看代码[BsonDefaultValue(This is a default title)] public string title { get; set; } 当写入的时候如果映射中不传入值则数据库会把这个默认值存到数据集中。3. BsonRepresentation属性这个属性是用来在映射类中的数据类型和数据集中的数据类型做转换的。看代码[BsonRepresentation(BsonType.String)] public int favor { get; set; } 这段代表表示在映射类中favor字段是int类型的而存到数据集中会保存为string类型。前边Decimal转换和枚举转换就是用的这个属性。4. BsonIgnore属性这个属性用来忽略某些字段。忽略的意思是映射类中某些字段不希望被保存到数据集中。看代码[BsonIgnore] public string ignore_string { get; set; } 这样在保存数据时字段ignore_string就不会被保存到数据集中。六、总结数据映射本身没什么新鲜的内容但在MongoDB中如果用好了映射开发过程从效率到爽的程度都不是SQL可以相比的。正所谓一入Mongo深似海从此SQL是路人。 谢谢大家全文完 本文的配套代码在https://github.com/humornif/Demo-Code/tree/master/0015/demo点「在看」让更多人因你而受益↘  ↘  ↘
http://www.pierceye.com/news/471124/

相关文章:

  • 网站如何关闭东莞网站开发推荐
  • 自己开网站能赚钱吗网站界面设计描述
  • 二手交易网站建设方案ppt网站备案的作用
  • 北京行业网站建设临沂谁会做网站
  • 网站备案 游戏修改wordpress字体
  • 福建微网站建设价格宝山专业网站建设
  • 做采集网站难不关键词做网站名字
  • 怎么做律师事务所的网站用凡科做网站好吗
  • 免费做网站公司ydwzjs政务网站的建设
  • 企业网站设计总结西安做网站哪里便宜
  • wordpress 电影下载站济南最新消息
  • 怎样做企业的网站公司部门解散
  • 三亚中国检科院生物安全中心门户网站建设什么是响应式网站
  • 为什么要建设公司网站怎么制作图片视频和配音乐
  • 建设项目环境影响登记表备案系统网站论坛门户网站开发
  • 铁岭网站建设建设云企业服务平台
  • 响应式网站制作方法泰安明航网络科技有限公司
  • 建设网站需要几级安全等保深圳网站开发招聘
  • 无锡网站建设制作公司甘肃省建设工程网站
  • 广州微信网站建设哪家好公司网站排名优化手段
  • 深圳市路桥建设集团有限公司招标采购网站crntos wordpress
  • 广告网站制作报价深圳建筑设计平台网站
  • 网站ns记录南宁企业建站模板
  • 网站服务建设目前做哪些网站能致富
  • 专业网站定制公司深圳网页制作服务
  • 白云网站(建设信科网络)网页工具在哪里
  • 食品网站策划网站建设送企业邮箱吗
  • 天津自贸区建设局网站手机网站导航设计
  • 企业网站建设制作大连网站建设吗
  • 做网页兼职网站有哪些建设网站需要花费