安装教程:http://www.runoob.com/mongodb/mongodb-window-install.html
下载地址:http://dl.mongodb.org/dl/win32/x86_64 第一个就好
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace DBI.SaaS.ExternalService.BigData
{
/// <summary>
/// MongoDb帮助类
/// </summary>
public class MongoDBHelper
{
private static readonly string connStr = "mongodb://127.0.0.1:27017";//GlobalConfig.Settings["mongoConnStr"];
private static readonly string dbName = "Holworth";//GlobalConfig.Settings["mongoDbName"];
private static IMongoDatabase db = null;
private static readonly object lockHelper = new object();
private MongoDBHelper() { }
public static IMongoDatabase GetDb()
{
if (db == null)
{
var client = new MongoClient(connStr);
db = client.GetDatabase(dbName);
}
return db;
}
public static void DropDb()
{
var client = new MongoClient(connStr);
client.DropDatabase(dbName);
}
}
public class MongoDbHelper<T> where T : Framework.Domain.Entity
{
private IMongoDatabase db = null;
private IMongoCollection<T> collection = null;
public string CreateIndex(Expression<Func<T, object>> expression)
{
string idx = collection.Indexes.CreateOne(Builders<T>.IndexKeys.Ascending(expression));
return idx;
}
public void DropIndex(string name)
{
collection.Indexes.DropOne(name);
}
public void DropIndexAll()
{
collection.Indexes.DropAll();
}
public void DropColleaction()
{
db.DropCollection(typeof(T).Name);
}
public MongoDbHelper()
{
this.db = MongoDBHelper.GetDb();
collection = db.GetCollection<T>(typeof(T).Name);
}
/// <summary>
/// 新增
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public T Insert(T entity)
{
var flag = ObjectId.GenerateNewId();
entity.GetType().GetProperty("ObjectId").SetValue(entity, flag);
entity.CreateDate = DateTime.Now;
collection.InsertOneAsync(entity);
return entity;
}
/// <summary>
/// 修改
/// </summary>
/// <param name="id"></param>
/// <param name="field"></param>
/// <param name="value"></param>
public void Modify(string id, string field, string value)
{
var filter = Builders<T>.Filter.Eq("Id", ObjectId.Parse(id));
var updated = Builders<T>.Update.Set(field, value);
UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
public void Update(T entity)
{
try
{
var old = collection.Find(e => e.ObjectId.Equals(entity.ObjectId)).ToList().FirstOrDefault();
foreach (var prop in entity.GetType().GetProperties())
{
var newValue = prop.GetValue(entity);
var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
if (newValue != null)
{
if (oldValue == null)
oldValue = "";
if (!newValue.ToString().Equals(oldValue.ToString()))
{
old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
}
}
}
old.LastModDatetime = DateTime.Now;
var filter = Builders<T>.Filter.Eq("ObjectId", entity.ObjectId);
ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
}
catch (Exception ex)
{
var aaa = ex.Message + ex.StackTrace;
throw;
}
}
/// <summary>
/// 删除
/// </summary>
/// <param name="entity"></param>
public void Delete(T entity)
{
var filter = Builders<T>.Filter.Eq("ObjectId", entity.ObjectId);
collection.DeleteOneAsync(filter);
}
/// <summary>
/// 根据id查询一条数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public T QueryOne(string id)
{
return collection.Find(a => a.ObjectId == ObjectId.Parse(id)).ToList().FirstOrDefault();
}
/// <summary>
/// 查询所有数据
/// </summary>
/// <returns></returns>
public List<T> QueryAll(Expression<Func<T, bool>> express = null)
{
List<T> list = null;
if (express == null)
list = collection.Find(a => true).ToList();
else
{
list = collection.Find(express).ToList();
}
return list;
}
/// <summary>
/// 根据条件查询一条数据
/// </summary>
/// <param name="express"></param>
/// <returns></returns>
public T QueryByFirst(Expression<Func<T, bool>> express)
{
return collection.Find(express).ToList().FirstOrDefault();
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="list"></param>
public void InsertBatch(List<T> list)
{
collection.InsertMany(list);
}
public void InsertBatchAsync(List<T> list)
{
collection.InsertManyAsync(list);
}
/// <summary>
/// 根据Id批量删除
/// </summary>
public void DeleteBatch(List<ObjectId> list)
{
FilterDefinition<T> filter = Builders<T>.Filter.In("Id", list);
collection.DeleteMany(filter);
}
public void DeleteBatchAsync(List<ObjectId> list)
{
FilterDefinition<T> filter = Builders<T>.Filter.In("Id", list);
collection.DeleteManyAsync(filter);
}
public void DeleteAll()
{
collection.DeleteMany(x => true);
}
public void DeleteAllAsync()
{
collection.DeleteManyAsync(x => true);
}
}
public interface MongoBaseEntity
{
ObjectId ObjectId { get; set; }
string UpdateTime { get; set; }
string CreateTime { get; set; }
}
}
protected void Button2_Click(object sender, EventArgs e)
{
var Dao = ctx["CommonService"] as Framework.IService.ICommonService;
MongoDbHelper<MktPriceMarketData> datas = new MongoDbHelper<MktPriceMarketData>();
datas.CreateIndex(x=>x.ObjectId);
datas.DeleteAll();
List<MktPriceMarketData> list = new List<MktPriceMarketData>();
list = Dao.ExecuteRowMapper(new Framework.QueryInfo() { CustomSQL = "select * from mkt_price_market_data " }, new MktPriceMarketData()).ToList();
var list1 = Dao.ExecuteRowMapper(new Framework.QueryInfo() { CustomSQL = "select * from mkt_price_market_data " }, new MktPriceMarketData()).ToList();
list.AddRange(list1);
long i = 0;
foreach (var item in list)
{
item.Id = i++.ToString();
}
try
{
datas.InsertBatch(list);
var list2 = datas.QueryAll();
}
catch (Exception ex)
{
throw;
}
//TestMemcache();
return;
}
}