Saturday, May 16, 2015

MongoDB Useful CRUD Extension pattern using LINQ

Say if we want to remove some documents from a collection, we can use collection.Remove() by passing in a query like so

articles.Remove(Query<Article>.EQ ( a => a.PublishedDate < DateTime.Today ));

We can create a LINQ extension class for the MongoDB collection

public static class MongoExtensions
{
    public static WriteConcernResult Remove<T> ( this MongoCollection<T> collection,
                                                                                 Expression<Func<T, bool>> query)
    {
          return collection.Remove(Query<T>.Where(query));
    }
}


Then you can have your zen coding moments!

articles.Remove( a => a.PublishedDate < DateTime.Today );

No comments:

Post a Comment