MangoDB的C#Driver驱动简单例子

时间:2022-05-11 19:12:44

以下是本人学习C#Driver驱动简单的学习例子。GridFS的增删查操作 和 表的增删查改操作。

MangoDB的C#Driver驱动简单例子

MangoDB的C#Driver驱动简单例子

    public class MongoServerHelper
{
public static string dataBase = "File";
public static string fsName = "fs"; private static string _IP = "192.168.1.60";
private static int _port = ; public MongoServer GetMongoServer()
{
MongoServerSettings Settings = new MongoServerSettings();
Settings.Server = new MongoServerAddress(_IP, _port);
//最大连接池
Settings.MaxConnectionPoolSize = ;
//最大闲置时间
Settings.MaxConnectionIdleTime = TimeSpan.FromSeconds();
//链接时间
Settings.ConnectTimeout = TimeSpan.FromSeconds();
//等待队列大小
Settings.WaitQueueSize = ;
//socket超时时间
Settings.SocketTimeout = TimeSpan.FromSeconds();
//队列等待时间
Settings.WaitQueueTimeout = TimeSpan.FromSeconds();
//操作时间
Settings.OperationTimeout = TimeSpan.FromSeconds();
MongoServer server = new MongoServer(Settings);
return server;
}
}
    public class BaseDAL
{
public MongoServerHelper mongoServerHelper = new MongoServerHelper();
private MongoServer server = null; public BaseDAL()
{
server = mongoServerHelper.GetMongoServer();
} /// <summary>
/// 新增
/// </summary>
public Boolean Insert(String collectionName, BsonDocument document)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
collection.Insert(document);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 新增
/// </summary>
public Boolean Insert<T>(String collectionName, T t)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
var collection = database.GetCollection<T>(collectionName);
try
{
collection.Insert(t);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 批量新增
/// </summary>
public IEnumerable<WriteConcernResult> Insert<T>(String collectionName, List<T> list)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
var collection = database.GetCollection<T>(collectionName);
try
{
IEnumerable<WriteConcernResult> result = collection.InsertBatch(list);
server.Disconnect();
return result;
}
catch
{
server.Disconnect();
return null;
}
} /// <summary>
/// 修改
/// </summary>
public WriteConcernResult Update(String collectionName, IMongoQuery query, QueryDocument update)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
var new_doc = new UpdateDocument() { { "$set", update } };
//UpdateFlags设置为Multi时,可批量修改
var result = collection.Update(query, new_doc, UpdateFlags.Multi);
server.Disconnect();
return result;
}
catch
{
return null;
}
} /// <summary>
/// 移除匹配的集合
/// </summary>
public Boolean Remove(String collectionName, IMongoQuery query)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
collection.Remove(query);
server.Disconnect();
return true;
}
catch
{
server.Disconnect();
return false;
}
} /// <summary>
/// 分页查询
/// </summary>
public List<T> GetPageList<T>(String collectionName, IMongoQuery query, string sort, bool isDesc, int index, int pageSize, out long rows)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
List<T> list;
try
{
rows = collection.FindAs<T>(query).Count();
if (isDesc)
{
list = collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
}
else
{
list = collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).SetSkip(index).SetLimit(pageSize).ToList();
}
server.Disconnect();
return list; }
catch
{
rows = ;
server.Disconnect();
return null;
}
} /// <summary>
/// 查询对象集合
/// </summary>
public List<T> GetList<T>(String collectionName, IMongoQuery query, string[] sort, bool isDesc)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
List<T> list;
try
{
if (isDesc)
{
list= collection.FindAs<T>(query).SetSortOrder(SortBy.Descending(sort)).ToList();
server.Disconnect();
return list;
}
else
{
list =collection.FindAs<T>(query).SetSortOrder(SortBy.Ascending(sort)).ToList();
server.Disconnect();
return list;
}
}
catch
{
return null;
}
} /// <summary>
/// 总数
/// </summary>
public long Count(string collectionName, IMongoQuery query)
{
server.Connect();
MongoDatabase database = server.GetDatabase(MongoServerHelper.dataBase);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
try
{
server.Disconnect();
return collection.Count(query);
}
catch
{
server.Disconnect();
return ;
}
}
}
    public class BaseEntity
{
/// <summary>
/// 基类对象的ID,MongoDB要求每个实体类必须有的主键
/// </summary>
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
}
    public class User : BaseEntity
{
public string Name { get; set; }
public int No { get; set; }
public DateTime Time { get; set; }
public double Money { get; set; }
}
            BsonDocument doc = new BsonDocument()
{
{"Name","Mongo"},
{"No",},
{"Time",DateTime.Now},
{"Money",102.123}
};
_daoMongo.Insert("MongoUser", doc); User model = new User() { Name = "MongoT", No = , Time = DateTime.Now, Money = 11.22 };
_daoMongo.Insert<User>("MongoUser", model);
List<User> List = new List<User>();
for (int i = ; i < ; i++)
{
List.Add(new User() { Name = "MongoT" + i, No = i, Time = DateTime.Now, Money = 11.22 });
}
_daoMongo.Insert<User>("MongoUser", List); QueryDocument update = new QueryDocument() { { "Name", "" }, { "Money", 1000.555 } };
_daoMongo.Update("MongoUser", Query<User>.EQ(m => m.No, ), update); _daoMongo.Remove("MongoUser", Query<User>.EQ(m => m.No, )); long aa = _daoMongo.Count("MongoUser", Query<User>.GT(m => m.No, )); List<User> list = _daoMongo.GetList<User>("MongoUser", Query<User>.GT(m => m.No, ), new string[] { "No" }, true);
List<User> list2 = _daoMongo.GetPageList<User>("MongoUser", Query<User>.GT(m => m.No, ), "No", true, , , out aa);
    /// <summary>
/// GridFS文件处理
/// </summary>
public class GridFSHelper
{
private MongoServerHelper mongoServerHelper = new MongoServerHelper();
protected internal MongoServer server = null; public GridFSHelper()
{
server = mongoServerHelper.GetMongoServer();
} public string AddDoc(byte[] content, string ContentType, string fileName)
{
try
{
string fileID = Guid.NewGuid().ToString();
this.server.Connect();
MongoGridFSCreateOptions optioms = new MongoGridFSCreateOptions()
{
ChunkSize = ,
UploadDate = DateTime.Now.AddHours(),
ContentType = ContentType,
Id = fileID
};
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName }); using (MongoGridFSStream gfs = fs.Create(fileName, optioms))
{
gfs.Write(content, , content.Length);
}
return fileID;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
} public byte[] GetDoc(string fileID)
{
try
{
this.server.Connect();
MongoDatabase db = this.server.GetDatabase(MongoServerHelper.dataBase);
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName });
byte[] bytes = null;
MongoGridFSFileInfo info = fs.FindOneById(fileID);
using (MongoGridFSStream gfs = info.Open(FileMode.Open))
{
bytes = new byte[gfs.Length];
gfs.Read(bytes, , bytes.Length);
}
return bytes;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
} public bool DeleteDoc(string fileID)
{
if (string.IsNullOrEmpty(fileID))
return false; try
{
this.server.Connect();
MongoDatabase db = this.server.GetDatabase(MongoServerHelper.dataBase);
MongoGridFS fs = new MongoGridFS(this.server, MongoServerHelper.dataBase, new MongoGridFSSettings() { Root = MongoServerHelper.fsName });
fs.DeleteById(fileID);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.server != null)
this.server.Disconnect();
}
}
}
        public ActionResult Load()
{
HttpPostedFileBase hpf = Request.Files["fileUpload"];
string objectID;
objectID = _gridFSHelper.AddDoc(StreamToBytes(hpf.InputStream), hpf.ContentType, hpf.FileName);
return Content(objectID);
}

MangoDB的C#Driver驱动简单例子

MangoDB的C#Driver驱动简单例子

MangoDB的C#Driver驱动简单例子