C# 操作 MongoDB的示例demo

今项目使用Mongodb,C#操作MongoDB使用MongoDB.Driver.dll库(Nuget),写了个小Demo,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MongoDB.Driver;

namespace MongoBase
{
  internal class MongoBase
  {
    private static string _connStr = "mongodb://root:[email protected]:27017";
    private static string _dbName = "test";

    private static MongoUrl url = new MongoUrl(_connStr);
    private static MongoClient client = new MongoClient(url);
    public static IMongoDatabase db = client.GetDatabase(_dbName);
  }

  public class MongoHelper
  {
    public string Name => typeof(TEntity).Name;
    public IMongoCollection Collection => MongoBase.db.GetCollection(Name);
    public List Queryable => Collection.AsQueryable().ToList();

    public FilterDefinitionBuilder Filter => Builders.Filter;

    public UpdateDefinitionBuilder Update => Builders.Update;

    public ProjectionDefinitionBuilderProjection=> Builders.Projection;
  }


}
using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoBase
{
  public class EntityBase
  {
    public EntityBase()
    {
      _id = ObjectId.GenerateNewId();
      createTime = DateTime.Now;
      isDelete = false;
      id = _id.ToString();
    }
    [BsonId]
    public ObjectId _id { get; set; }
    public string id { get; set; }

    public DateTime? createTime { get; set; }

    public bool? isDelete { get; set; }


  }

}
using MongoBase;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace ConsoleApp5
{
  internal class Video : EntityBase
  {
    public string Title { get; set; }

    public string Category { get; set; }

    public int Minutes { get; set; }

    public string Comments { get; set; }
  }
}
using System;
using System.Collections.Generic;
using MongoBase;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;


namespace ConsoleApp5
{
  class Program
  {
    static void Main(string[] args)
    {
      MongoHelper

注:时间类型的属性,存入MongoDB后会比北京时间少8小时,是由于默认写入的是世界标准时间,可在时间类型属性上添加

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime createTime { get; set; }

的特性,这样取出来之后就是北京时间。

以上就是C# 操作 MongoDB的示例demo的详细内容,更多关于C# 操作 MongoDB的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(C# 操作 MongoDB的示例demo)