This is a quick, short and sharp post covering how to add data to Contacts in xDB, specifically to the Facets and Elements that come with Sitecore out-of-the-box. This post is to provide additional info to that goes with recent posts covering how to identify and merge Contacts in xDB and how to extend xDB to store custom data.
To give an idea how this can be applied in the real world I am using the following example for this series of blogs. We have a website where Users can order products online. In the purchase path there is a form to collect base information so we can fulfill their order; name, contact info, address, email address etc. We will also use this information update users’ Contacts with the information to build a picture of who the site’s users are. This update will occur when the user clicks Next on the form – save us running the risk of them not making it to the end of the purchase path.
Updating Sitecore Contacts
Writing data from our Order form to the Contact’s out-of-the-box Facets is actually pretty simple. Get the Contact (I’ve covered an robust way to do this) and call GetFacet using the Interface of the type passing in the name of the Facet. Setting some personal details is as below. Note: its your call if you want to overwrite the data each time.
Writing to MongoDB Elements is that simple, but it gets more complex when dealing with lists of data like Collections. Lets use an example. In xDB Addresses Facet consists of a Collection for the addresses and an Attribute to define a Preferred Address. The same the Email Addresses Facet. So in our example we want an entry for our Shipping Address.
With the Addresses Facet in hand, create the entry for Shipping Address (if its not present already). If the entry doesn’t exist an error will occur. On the entry set the values to the address details the user entered in the form. I found it to be good practice to set the preferred entry of Facet to be the one we are creating if one has not already been set.
Once the Contact has been updated you can leave the write to MongoDB to occur when the user’s session ends or call SaveAndReleaseContactToXdb() to do it immediately.
And that’s it!
Adding data to the default Facets of an xDB Contact. It’s pretty simple really. As I mentioned, be sure to check out the two related posts to learn how to extend xDB to store custom data, how to handle identifying users and how to persist data when merging two Contacts together.