Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using Norm;
using Norm.Responses;
using Norm.Collections;
using Norm.Linq;
public class MongoSession {
private Mongo _server;
MongoQueryProvider _provider;
public MongoSession() {
//set this connection as you need. This is left here as an example, but you could, if you wanted,
//put this in the web/app.config
_server = Mongo.Create("mongodb://");
_provider = MongoQueryProvider.Create(_server.Database);
public void CommitChanges() {
//mongo isn't transactional in this way... it's all firehosed
public void Delete<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new() {
var items = All<T>().Where(expression);
foreach (T item in items) {
public void Delete<T>(T item) where T : class, new() {
public void DeleteAll<T>() where T : class, new() {
public T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new() {
return new MongoQuery<T>(_provider).Where(expression).SingleOrDefault();
public IQueryable<T> All<T>() where T : class, new() {
return new MongoQuery<T>(_provider);
public void Add<T>(T item) where T : class, new() {
public void Add<T>(IEnumerable<T> items) where T : class, new() {
foreach (T item in items) {
public void Update<T>(T item) where T : class, new() {
_server.Database.GetCollection<T>().UpdateOne(item, item);
//this is just some sugar if you need it.
public T MapReduce<T>(string map, string reduce) {
T result = default(T);
var mr = _server.Database.CreateMapReduce();
MapReduceResponse response =
mr.Execute(new MapReduceOptions(typeof(T).Name) {
Map = map,
Reduce = reduce
MongoCollection<MapReduceResult<T>> coll = response.GetCollection<MapReduceResult<T>>();
MapReduceResult<T> r = coll.Find().FirstOrDefault();
result = r.Value;
return result;
public void Dispose() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment