Utilizing data extension points
The first thing I would consider is whether your data can be stored as part of the standard Sitecore entities.
Contact
The xDB contact has the following fields where you can store custom data that will be saved to MongoDB:
Interactions
If you use any of the above, you won't have to implement any MongoDB-specific code, as xDB will store and retrieve data for you.
Raw database access
xDB provides the MongoDbDriver
class (located in Sitecore.Analytics.Data.DataAccess.MongoDb
) that allows you to read and write to MongoDB directly. This is a part of the data access layer used by xDB itself.
Here's how you use it. First, get an instance of the driver:
var driver = MongoDbDriver.FromConnectionString("analytics");
You can also set up your own MongoDB connection string rather than using "analytics"
.
Then you get a collection instance:
MongoDbCollection collection = driver["YourCollectionName"];
Since MongoDB is schemaless, you can just work with a non-existing collection. It will be created on first access.
Once you have a collection object, you can do CRUD, as well as some extra data and schema operations.
Fetching data
MongoCursor<YourCustomData> cursor =
collection.FindAs<YourCustomData>(
Query.LTE("CreatedDate", DateTime.Now));
IList<YourCustomData> results = cursor.Skip(5).Take(10).ToList();
You can also use lambda expressions to refer to fields:
MongoCursor<YourCustomData> cursor =
collection.FindAs<YourCustomData>(
Query<YourCustomData>.EQ(_ => _.SomeField, "FieldValue"));
Inserting data
var data = new YourCustomData { SomeField = "SomeValue" };
collection.Insert(data);
Creating an index
collection.EnsureIndex(true, "DataFieldName");
MongoDbStorage
If you're fine with CRUD only, you can use a convenience wrapper around the MongoDbCollection
.
MongoDbCollection collection = MongoDbDriver.FromConnectionString(connectionStringName)["CollectionName"];
var storage = new MongoDbStorage<YourCustomData, CustomIdType>(collection);
MongoDbStorage
has the following methods:
- Insert
- Save
- Update
- Delete
- Load
- Count
Registering custom types in the driver
Note that the driver will serialize/deserialize data for you. But first, you will need to register your types using the helper methods provided by xDB:
MongoDbObjectMapper.Instance.RegisterModelExtension<YourCustomData>();
You can also specify the collection name to use and the way to get the identifier of your custom objects (that's what will be stored in _id
):
MongoDbObjectMapper.Instance.RegisterModelExtension<YourCustomData, CustomIdType>("CollectionName", d => d.CustomId);
Registering custom types is something that should be done once per application lifetime. You can register your types in a static constructor or in a custom initialize
pipeline processor.