Skip to content

Instantly share code, notes, and snippets.

@diegofrata
Forked from anonymous/Repository.fs
Last active December 10, 2015 06:28
Show Gist options
  • Save diegofrata/4394128 to your computer and use it in GitHub Desktop.
Save diegofrata/4394128 to your computer and use it in GitHub Desktop.
Very Simple MongoDB Repository for F#
open System.Collections
open System.Configuration
open System.Data.Entity.Design.PluralizationServices
open System.Linq
open FluentMongo.Linq
open MongoDB.Bson
open MongoDB.Driver
open MongoDB.Driver.Builders
module MongoRepository =
let mutable connectionStringName = "MongoDB"
let private db =
let connectionString = ConfigurationManager.ConnectionStrings.[connectionStringName].ConnectionString
MongoConnectionStringBuilder(connectionString) |> MongoDatabase.Create
let private collection<'a> =
let pluralizer = PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentCulture)
let n = typedefof<'a>.Name |> pluralizer.Pluralize
db.GetCollection<'a> n
let qry<'a> : IQueryable<'a> =
collection |> MongoCollectionExtensions.AsQueryable
let save item =
item |> collection.Save |> ignore
let removeById<'a> id =
let value = id |> BsonValue.Create
Query.EQ ("_id", value)
|> collection<'a>.Remove
|> ignore
let inline remove<'a when 'a : (member Id : ObjectId)> item =
(^a : (member Id : ObjectId) item) |> removeById
module RepositoryTest =
[<CLIMutable>]
type User = { Id : ObjectId; Name : string; Age : int; }
[<CLIMutable>]
type Place = { Id : ObjectId; Name : string; Address : string; }
let saveTest () =
{ Id = ObjectId.Empty; Name = "Diego Frata"; Age = 25 } |> MongoRepository.save
{ Id = ObjectId.Empty; Name = "Mundo Cervejeiro"; Address = "Av. Miruna, 51" } |> MongoRepository.save
let queryTest () =
query { for u in MongoRepository.qry<User> do
select u }
|> Seq.iter (fun u -> printf "%A %s %d" u.Id u.Name u.Age)
let removeTest () =
query { for u in MongoRepository.qry<User> do
select u
take 1 }
|> Seq.iter (fun u -> MongoRepository.remove u)
[<EntryPoint>]
let main argv =
do saveTest()
do queryTest()
do removeTest()
0
@diegofrata
Copy link
Author

This repository is intended to be used in projects where ONLY ONE MongoBD database is accessed. Imposing this limit creates the ability to implement the repository as module, making it simple to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment