C# 操作 MongoDB的示例demo
今项目使用Mongodb,C#操作MongoDB使用MongoDB.Driver.dll库(Nuget),写了个小Demo,如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Linq.Expressions; usingSystem.Text; usingMongoDB.Driver; namespaceMongoBase { internalclassMongoBase { privatestaticstring_connStr="mongodb://root:123456@127.0.0.1:27017"; privatestaticstring_dbName="test"; privatestaticMongoUrlurl=newMongoUrl(_connStr); privatestaticMongoClientclient=newMongoClient(url); publicstaticIMongoDatabasedb=client.GetDatabase(_dbName); } publicclassMongoHelper{ publicstringName=>typeof(TEntity).Name; publicIMongoCollection Collection=>MongoBase.db.GetCollection (Name); publicList Queryable=>Collection.AsQueryable().ToList(); publicFilterDefinitionBuilder Filter=>Builders .Filter; publicUpdateDefinitionBuilder Update=>Builders .Update; publicProjectionDefinitionBuilder Projection=>Builders .Projection; } }
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingMongoDB.Bson; usingMongoDB.Bson.Serialization.Attributes; namespaceMongoBase { publicclassEntityBase { publicEntityBase() { _id=ObjectId.GenerateNewId(); createTime=DateTime.Now; isDelete=false; id=_id.ToString(); } [BsonId] publicObjectId_id{get;set;} publicstringid{get;set;} publicDateTime?createTime{get;set;} publicbool?isDelete{get;set;} } }
usingMongoBase; usingMongoDB.Bson; usingMongoDB.Bson.Serialization.Attributes; namespaceConsoleApp5 { internalclassVideo:EntityBase { publicstringTitle{get;set;} publicstringCategory{get;set;} publicintMinutes{get;set;} publicstringComments{get;set;} } }
usingSystem; usingSystem.Collections.Generic; usingMongoBase; usingMongoDB.Bson; usingMongoDB.Driver; usingMongoDB.Driver.Linq; namespaceConsoleApp5 { classProgram { staticvoidMain(string[]args) { MongoHelper
注:时间类型的属性,存入MongoDB后会比北京时间少8小时,是由于默认写入的是世界标准时间,可在时间类型属性上添加
[BsonDateTimeOptions(Kind=DateTimeKind.Local)]
publicDateTimecreateTime{get;set;}
的特性,这样取出来之后就是北京时间。
以上就是C#操作MongoDB的示例demo的详细内容,更多关于C#操作MongoDB的资料请关注毛票票其它相关文章!