Working with custom MongoDB collections in Sitecore 8 using WebApi

The introduction of the xDB to the Sitecore eXperience Platform offer a ton of new options for us Sitecore developers. As a bonus we suddenly have a data store for anything at any time instead of either trying to make the data fit into Sitecore items or give up and go with a custom database. Now we can just use mongo for almost anything.

In this post I will show how extremely simple it is to get and set data in a custom mongo collection.

We start out with creating a simple class called Comment that we will use as example:

Then we create a repository that can get and set Comment objects in mongo.

The connection string to the mongodb containing the comments collection then need to be configured in connectionstrings.config:

Then we create a CommentApiController for getting and setting comments:

Finally we map the routes for the controller:

That is it! It is so extremely easy to work with mongo db while still being completely reliable.

The Repository that I just created as an example could also have been implemented as a Sitecore.Services.Core.IRepository that has been introduced in Sitecore.Services so it could be used in an EntityService. Read this great introduction post on EntityService by Mike Robbins if you haven’t already heard about this already.

A comment made by a visitor could also be stored directly on the Contact using the analytics API and not in a custom collection. This has only been made as an example and is not production ready code.

Anders Laub

Anders Laub Christoffersen

Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders has been nominated a Sitecore Technical MVP three years in a row for 2014, 2015 and 2016. Anders is now working as a Sr. Solutions Architect at Sitecore in Copenhagen.

One thought on “Working with custom MongoDB collections in Sitecore 8 using WebApi

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website