CRUDing in F# with MongoDb

Moko Sharma
3 min readJul 23, 2017

--

Introduction

I want to be able to take exoplanetary data, filter and store them in some digestible form for charting and calculations in an effort to discover other potentially inhabitable planets.

Source: http://io9.gizmodo.com/exoplanets-just-slightly-bigger-than-earth-are-surprisi-1582048404

Inspired by this extremely informative blogpost by Edgar Sánchez Gordón, I started experimenting with CRUD operations in F# and MongoDb. This blogpost highlights the ease of which I was able to get the ball rolling by getting basic CRUD operations working.

Why did I chose MongoDb? Because it’s web scale.

Setting Up

I used Visual Studio Code on a Mac with Ionide, PAKET, FAKE and Mono. For storage, I used MLab. The free tier of MLab gives us 0.5 GB of complementary MongoDb storage; this is more than enough to do some preliminary testing.

The dependencies that I installed via PAKET are:

  1. C# MongoDb Driver [ mongocsharpdriver ]
  2. F# MongoDB Driver [ MongoDb.FSharp ]

Once all preliminaries had been successfully completed, I grabbed the URI for the Database from MLab that’ll be our connection string.

Example of a Connection String from MLab

Note: You can refer to my previous blost posts [ here and here ] or Mr. Gordón’s post to create a new project, add dependencies and build with Vs Code, PAKET, FAKE, Ionide and Mono.

The test record will be extremely simple:

type PlanetData = { Id : BsonObjectId; Name : string }

We’ll be using testCollection of type IMongoCollection<PlanetData> as our handle to the database for our CRUD operations. Each of these CRUD operations are implemented below and, hopefully, should be fairly simple to understand.

Setting Up for the CRUD Operations

Create

Read

Note: Finding a document on an empty filter using “Builders.Filter.Empty” will get us back all documents in the collection.

Update

The return type of the UpdateOne or UpdateMany method is an “UpdateResult” type that contains meta data about the update process with the following properties. The implementation for UpdateResult can be found here.

Delete

Similar to the UpdateResult, the methods in the Delete bucket get us back the DeleteResult type; the implementation of which can be found here:

Conclusion

Overall my implementation looks like:

It was fairly straight forward to get started with MongoDb with F#.

Marrying these CRUD functions to a WebServer like Suave, as you may have guessed, is probably going to be the next step.

--

--

Moko Sharma

C#, Python, F# and Data Science Fanatic. Data Science @ UWisconsin. ECE @ Carnegie Mellon Grad. Formerly in FinTech.