MongoDB 数据库实现实例
/// <summary>
/// Summary description for Corpus
/// </summary>
public class CorpusMongoDB
{
/// <summary>
/// 数据库的实例
/// </summary>
private IMongoDatabase mongoDB;
private string TableName;
public CorpusMongoDB(string Mongo_User, string Mongo_Pass, string Mongo_Host, string Mongo_DbName, string tableName)
{
this.mongoDB = new MongoDb().GetDataBase(Mongo_User, Mongo_Pass, Mongo_Host, Mongo_DbName);
this.TableName = tableName;
}
public List<CorpusHtml> FindPageList(int pageIndex, int pageSize, ref long TotalCount, string startTime = "", string endTime = "", string seach = "")
{
try
{
List<CorpusHtml> list = new List<CorpusHtml>();
var collection = mongoDB.GetCollection<CorpusHtml>(TableName);
//判断键值是否存在
var filter = Builders<CorpusHtml>.Filter.Eq("isdelete", 0);
if (!string.IsNullOrEmpty(startTime))
{
filter = filter & Builders<CorpusHtml>.Filter.Gte("creatTime", startTime);
}
if (!string.IsNullOrEmpty(endTime))
{
filter = filter & Builders<CorpusHtml>.Filter.Lte("creatTime", endTime);
}
if (!string.IsNullOrEmpty(seach))
{
filter = filter & Builders<CorpusHtml>.Filter.Eq("keyWord", seach);
}
//如页序号为0时初始化为1
pageIndex = pageIndex == 0 ? 1 : pageIndex;
int skip = (pageIndex - 1) * pageSize;
list = collection.Find(filter).Skip(skip).Limit(pageSize).ToList();
TotalCount = collection.Count(filter);
return list;
}
catch (Exception ex)
{
return null;
}
}
public CorpusHtml getCorpusInfoByid(string id)
{
CorpusHtml corpusInfo = new CorpusHtml();
try
{
var collection = mongoDB.GetCollection<CorpusHtml>(TableName);
var filter = Builders<CorpusHtml>.Filter.Eq("id", ObjectId.Parse(id));
corpusInfo = collection.Find(filter).ToList().FirstOrDefault();
return corpusInfo;
}
catch (Exception ex)
{
return corpusInfo;
}
}
public bool DeleteByid(string id)
{
bool re = false;
var collection = mongoDB.GetCollection<CorpusHtml>(TableName);
var filter = Builders<CorpusHtml>.Filter.Eq("id", ObjectId.Parse(id));
var updated = Builders<CorpusHtml>.Update.Set("isdelete", "1");
var result = collection.UpdateOne(filter, updated);
if (Convert.ToInt32(result.ModifiedCount) > 0)
{
re = true;
}
return re;
}
public bool DeleteBykeyword(string keyword)
{
bool re = false;
var collection = mongoDB.GetCollection<CorpusHtml>(TableName);
var filter = Builders<CorpusHtml>.Filter.Eq("keyword", keyword);
var updated = Builders<CorpusHtml>.Update.Set("isdelete", "1");
var result = collection.UpdateOne(filter, updated);
if (Convert.ToInt32(result.ModifiedCount) > 0)
{
re = true;
}
return re;
}
}