Skip to content

Instantly share code, notes, and snippets.

@ducas
Created April 10, 2014 23:53
Show Gist options
  • Save ducas/10432885 to your computer and use it in GitHub Desktop.
Save ducas/10432885 to your computer and use it in GitHub Desktop.
Generic WebAPI controller to provide a REST interface for MongoDB collections
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Web.Core
{
public abstract class MongoApiController<T> : ApiController
{
private readonly MongoDatabase _db;
private readonly string _collectionName;
protected MongoApiController(MongoDatabase db, string collectionName)
{
_db = db;
_collectionName = collectionName;
}
public virtual IEnumerable<T> Get(int? skip = null, int? take = null, string fields = null)
{
var cursor = _db.GetCollection<T>(_collectionName)
.FindAll();
if (skip != null) cursor = cursor.SetSkip(skip.Value);
if (take != null) cursor = cursor.SetLimit(take.Value);
if (fields != null) cursor = cursor.SetFields(fields.Split(','));
return cursor
.ToArray();
}
public virtual T Get(string id)
{
return _db.GetCollection<T>(_collectionName).FindOneById(BsonValue.Create(id));
}
public virtual void Post(T document)
{
_db.GetCollection<T>(_collectionName).Save(document);
}
public virtual IHttpActionResult Put(T document)
{
_db.GetCollection<T>(_collectionName).Insert(document);
return Ok(document);
}
public virtual void Delete(string id)
{
_db.GetCollection<T>(_collectionName).Remove(Query.EQ("_id", BsonValue.Create(id)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment