I was wondering if anyone has a clean way to handle removing and updating documents using FluentMongo?
I am creating a repository layer using FluentMongo; however, not being able to remove or update documents is proving troublesome. Perhaps I missed a way to handle this while maintaining a proper repository pattern?
public interface IRepository : IDisposable
{
IQueryable<T> All<T>() where T : class, new();
void Delete<T>(Expression<Func<T, bool>> expression)
where T : class, new();
void Update<TEntity>(TEntity entity) where TEntity : class, new();
}
Thank you.
The simplest way will be to wrap the standard MongoCollection behind your repository methods. Since your repository is typed you can just create a typed collection and remove the documents from that collection. Here is a sample implementation.
MongoCollection<T> collection = mongoserver.GetCollection<T>();
public void Delete(string id)
{
this.collection.Remove(Query.EQ("_id", id));
}
public void Delete(T entity)
{
this.Delete(entity.Id);
}
added by balexandre on 27 July 2013
using FluentMongo, there a property that retrieves the MongoCollection<T>
that is useful for advanced queries, for example, if we want to delete all our documents in our collection, we would write something like this:
public void DeleteAll() {
var collection = myRepository.Collection;
collection.RemoveAll();
}
if you want to return a confirmation that all documents were indeed deleted use the Ok
property
public bool DeleteAll() {
var collection = myRepository.Collection;
return collection.RemoveAll().Ok;
}