When you think of MongoDB, the NoSQL database that provides an agile development experience typically associated with NodeJS developement, do you think of Xamarin?

Up until a couple weeks ago, my answer was no. Turns out though we can add MongoDB to the ever growing list of database platform choices when building Xamarin apps!

Show Me The Goods!

To jump to the skinny of it, check out this quick start article on using Xamarin with Azure Cosmos DB and the MongoDB API on Microsoft's documentation site.

You can also check out the source code for a fully functioning app here.

The Basic Overview!

To get started with MongoDB, download the MongoDB .NET SDK from NuGet into each of your projects.

You'll also need to create an Azure Cosmos DB account and create a MongoDB API database.

Get a free Azure account here!

Databases and Collections

Data in MongoDB is organized into databases and collections. To obtain a reference to each you'll use the MongoClient object.

// Initialize the client
var mongoClient = new MongoClient(settings);

// This will create or get the database
var db = mongoClient.GetDatabase(dbName);

// This will create or get the collection
var collectionSettings = new MongoCollectionSettings { ReadPreference =  ReadPreference.Nearest };

TasksCollection = db.GetCollection<MyTask>(collectionName, collectionSettings);

Notice that the collection is strongly typed to MyTask!

Reading Data

Reading data is done through the collection. An easy way to grab data is via our old friend LINQ.

var tasks = await TasksCollection
                    .AsQueryable()
                    .Where(t => t.Complete == false)
                    .Where(t => t.DueDate < date)                    
                    .ToListAsync();

Notice the async and the await functionality - no blocking the UI thread here!

Writing Data

Again, writing is accomplished through the collection.

await TasksCollection.InsertOneAsync(task);
await TasksCollection.ReplaceOneAsync(t => t.Id.Equals(task.Id), task);

Summing It Up

This was the briefest of brief overviews of using MongoDB with a Xamarin app. To learn more check out the documentation to learn more about using the MongoDB API with Xamarin. And learn more about MongoDB with Azure Cosmos DB here!

MongoDB with Xamarin - add it to your toolbelt of database choices!!