F# ❤️ MongoDB
Recently I’ve faced several problems working with MongoDB.Driver for .NET from F# project and here I’ll try to describe how you could make it all work fine.
First of all download and install mongodb from https://www.mongodb.com/ with standard configuration you like.
There’s a verbose guide and documentation that you could find about mongodb and how it works on the official web site (https://docs.mongodb.com/getting-started/shell/).
After you’ve completed the installation — create an F# script and load mongodb .NET packages using nuget. You’ll need MongoDB.Driver, MongoDB.Driver.Core and MongoDB.Bson.
Start the script with the following:
So now let’s try to insert some data to the database, let’s create a new type Movie:
Now we could insert some values to our db, we’ll need a connection string (“mongodb://localhost” is default for local):
So now we have db collection which is just a proxy that acts like a collection, but it’s really insert a record to a database if we’ll use its InsertOne method.
Now we can check that the data inserted successfully using shell command:
- cd <mongo bin path>
- use MoviesDb
- movies.find()
There are some problems with type conversion from mongodb to f# types, so I haven’t found other solution except getting BsonDocument and then mapping it manually to our domain model type.
Finally, we get a seq of Movie elements and can work with them.
After that I’ve made some modification to make it simpler, so now we have a domain model like this (which is more like good F# type):
And now we save every Movie as a BsonDocument, so we convert it from Movie to BsonDocument
From this point we have to convert Movie to BsonDocument before insertion and convert it back at every read: