1.安装 mongodb driver package
2. 使用Wrapper 类:
public class MongoDbWrapper : IDisposable
{
private MongoServer _server;
private MongoDatabase _db;
public MongoDbWrapper()
{
var uri = ConfigurationSettings.AppSettings["mongoUrl"];
var url = new MongoUrl(uri);
var client = new MongoClient(url);
_server = client.GetServer();
_db = _server.GetDatabase(url.DatabaseName);
}
public MongoDbWrapper BatchAdd(T[] objArray, string collectionName)
{
var collection = _db.GetCollection(collectionName);
collection.InsertBatch(objArray);
return this;
}
public MongoDbWrapper Add(T obj, string collectionName)
{
var collection = _db.GetCollection(collectionName);
collection.Insert(obj);
return this;
}
///
/// e.g. { "Age", new BsonDocument { { "$gte", 10 } } }
///
///
///
public void DeleteBy(Expression> whereExp, string collectionName)
{
var collection = _db.GetCollection(collectionName);
collection.Remove(Query.Where(whereExp));
}
public void Update(IMongoQuery query, string collectionName, T newObj) where T : IMongoUpdate
{
var collection = _db.GetCollection(collectionName);
collection.Update(query, newObj);
}
public IEnumerable Search(Expression> whereExp, string collectionName)
{
var collection = _db.GetCollection(collectionName);
return collection.Find(Query.Where(whereExp)).ToList();
}
public T Single(Expression> whereExp, string collectionName)
{
return Search(whereExp, collectionName).Single();
}
public void RemoveCollection(string collectionName)
{
_db.DropCollection(collectionName);
}
public void Dispose()
{
_server.Disconnect();
}
} 3 一些相关操作的用法示例
查询 var driver = dbWrapper.Single(d => d.Name == name, DbCollectionName.For ()); var drivers = dbWrapper.Search (d => d.Name == name, DbCollectionName.For ()); 删除 dbWrapper.DeleteBy (j => j.Id == id, DbCollectionName.For ()); 从集合移除 var updatingNw = Update .Pull(nw => nw.Jobs, aJobFromQueue); dbWrapper.Update(Query .Where(n => n.Name == Name), DbCollectionName.For (), updatingNw); 添加新项到集合 var updatingDp = Update .AddToSet (d => d.PendingJobs, aJobFromQueue); dbWrapper.Update(Query .Where(d => d.Name == name), DbCollectionName.For (), updatingDp); 更新 dbWrapper.Update(Query .Where(n => n.Name == Name), DbCollectionName.For (), updatingNw);
以上就是MongoDb C# Wrapper 类 (MongoDb Driver 1.9)的内容,更多相关内容请关注PHP中文网(www.php.cn)!










