MongoDBHelper

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;

public class MongoDBHelper : IDisposable
{
private Mongo _mongo;
private IMongoDatabase _db;
private static readonly string connString = "Server=127.0.0.1";//默认的数据库链接
private static readonly string dbName = "NewsDB";//默认的数据库
public MongoDBHelper()
: this(connString, dbName) //可以给定默认的链接字符串和名称
{

}
/// <summary>
/// 连接MongoDB
/// </summary>
/// <param name="dbName">数据库名称,服务器使用默认连接</param>
public MongoDBHelper(string dbName)
{
_mongo = new Mongo(connString);
if (!string.IsNullOrEmpty(dbName))
_db = _mongo.GetDatabase(dbName);
else
throw new ArgumentNullException("DBName 为空...");
}
/// <summary>
/// 连接MongoDB
/// </summary>
/// <param name="connString">连接字符串</param>
/// <param name="dbName">数据库名称</param>
public MongoDBHelper(string connString, string dbName)
{
if (!string.IsNullOrEmpty(connString))
_mongo = new Mongo(connString);
else
throw new ArgumentNullException("connectionString为空...");
_mongo.Connect();
if (!string.IsNullOrEmpty(dbName))
_db = _mongo.GetDatabase(dbName);
else
throw new ArgumentNullException("DBName 为空...");
}

/// <summary>
/// 获取指定数据库的集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>() where T : class
{
return _db.GetCollection<T>();
}
/// <summary>
/// 获取指定数据库的集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>(string name) where T : class
{
return _db.GetCollection<T>(name);
}
/// <summary>
/// 根据指定的名称切换数据库
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
public IMongoDatabase ChangeDB(string dbName)
{
if (!string.IsNullOrEmpty(dbName))
_db = _mongo.GetDatabase(dbName);
else
throw new ArgumentNullException("DBName为空...");
return _db;
}



#region IDisposable 成员

public void Dispose()
{
if (_mongo != null)
{
_mongo.Dispose();
_mongo = null;
}
}

#endregion
}

 

posted @ 2011-12-05 15:49  晓风拂月  阅读(1055)  评论(0编辑  收藏  举报