Simple-MongoDB – Part 2, Anonymous types, JSON, Embedded entities and references

This is the second article of me showing some features in the Simple-MongoDB driver. This time I will explore more ways of inserting data. More specifically, I will look at how-to insert Anonymous types as well as how-to insert entities described with JSON. Finally we will look at how to deal with embedded documents and relationships between entities, so called references.

Other writings in this series

Sample code

The sample code from this second article, is available for download here. Note! It also contains the code from previous parts in this series, but there has been some updates to the code, hence if you want to get your hands on the code for a specific article, use the download link in that specific article.

Flexibility

One of my goals with my driver was that it shouldn’t be tied to a certain key-value based class, like the Document-class in the MongoDB-CSharp-driver. I know that the team behind that driver, currently are implementing this as well. Simple-MongoDB relies on JSON.Net from Newtonsoft for dealing with serialization and deserialization of objects, hence I get support for dealing with anonymous types, JSON etc. Let’s look at how it get reflected in the API.

Anonymous types

The Entitystore lets you store anonymous types but will then not be able to automatically insert the document in the correct collection, which means that you have to manually specify the entity name. Note, that I wrote “the entity name” and NOT the collection name. Why? Because the Entitystore works with entities and will i.e pluralize the specified entity name (if you haven’t turned off pluralization, which is enabled by default).

Insert using anonymous type

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession(Constants.ConnectionStringName))
{
    var entityStore = new SimoEntityStore(session, Constants.DatabaseName);

    var note = new
                    {
                        Text = "This is a note, created using anonymous type.",
                        Tags = new[] { "Anonymous types", "Part 2" }
                    };

    entityStore.Insert("Notes", note);
}

Raw JSON

You can of course write/generate the JSON and pass that to the Entitystore. Again, just as with anonymous types, you have to specify the entity name.

There's also a class "SimoJson" that takes a raw JSON-string in the constructor. If you are dealing with raw JSON, it's preferred to use the SimoJson-class.

Insert using raw JSON

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession(Constants.ConnectionStringName))
{
    var entityStore = new SimoEntityStore(session, Constants.DatabaseName);

    var rawJson = @"{ 
        Text : ""This is a note, created using raw Json-string."", 
        Tags : [""Raw Json-string"", ""Part 2""] }";

    entityStore.Insert("Notes", rawJson);
}

Insert using raw JSON

var json = new SimoJson(@"{ 
    Text : ""This is a note, created using SimoJson-type."", 
    Tags : [""SimoJson-type"", ""Part 2""] }");

entityStore.Insert("Notes", json);

Embedded documents

MongoDB supports embedded documents, and I like to see them as value-object (as in the context of Domain-driven design). The embedded document has the same lifetime as the entity that it's assigned to, hence it's not the same as a relationship.

Insert a Note with an embedded Note

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession(Constants.ConnectionStringName))
{
    var entityStore = new SimoEntityStore(session, Constants.DatabaseName);

    var note = new Note
                        {
                            Text = "This is a note with an embeded note, created using entity.",
                            Tags = new[] { "Note with embeded note", "Part 2" },
                            SubNote = new Note{Text = "This is a subnote that is embeded."}
                        };

    entityStore.Insert<Note>(note);
}

References

MongoDB supports references and to make use of them in Simple-MongoDB, you consume the SimoReference-class or the SimoReference-class. The generic version lets you specify the type of the _id-field. Currently, it supports:

  • Guid
  • int
  • long
  • string

Read more about the different types.

To use the standard MongoDB _id-hash, use the SimoReference-class. It will generate the hash from date-time, computer, sequence etc. The Reference holds information about, in which collection the referenced document exists and which _id-value it has.

Insert a Note with a reference

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession(Constants.ConnectionStringName))
{
    var entityStore = new SimoEntityStore(session, Constants.DatabaseName);

    var user = new User {Username = "daniel"};

    var note = new Note
    {
        Text = "This is a note with an embeded note, created using entity.",
        Tags = new[] { "Note with embeded note", "Part 2" },
        WriterReference = entityStore.Reference<User>(user._id)
    };

    entityStore.Insert(user);
    entityStore.Insert(note);
}

The EntityStore.Reference function uses generics to specify to collection and the _id-value comes from the entity. Both Note and User extends Entity, which contains a property _id : SimoId. I use the SimoAutoId as the statebag so that I don't have to manually ensure that the _id : SimoId gets a generated _id-value. I could have done this in the constructor by using SimoId.NewId().

One simple query

So, I will finish with showing you how-to perform queries using an Entity as template. The next article will deal with the various querying techniques, and by then I will hopefully have simplified the querying of references.

Query using Entity as template

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession(Constants.ConnectionStringName))
{
    var entityStore = new SimoEntityStore(session, Constants.DatabaseName);
    var selector = new Note
    {
        _id = null,
        Text = "This is a note with an embeded note, created using entity."
    };

    var notes = entityStore.Find<Note>(selector);
}

The _id is autogenerated in the Note's base class Entity, and we want to query all notes having the text, hence we need to null the _id.

That's it for now. Don't forget to download the sample-code.

//Daniel

About these ads

7 thoughts on “Simple-MongoDB – Part 2, Anonymous types, JSON, Embedded entities and references

  1. Pingback: DotNetShoutout

  2. Pingback: Tweets that mention Simple-MongoDB – Part 2, Anonymous types, JSON, Embedded entities and references « Daniel Wertheim -- Topsy.com

  3. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #585

  4. Pingback: progg.ru

  5. Pingback: Random Links #181 | YASDW - yet another software developer weblog

  6. Thanks for this, it’s very cool. What about typed reference collections? Atm I would use a list of SimoReference:s yes? But that only gives me the collection name and id for each reference. How about an IList Comments for a Post object for example?

    • Hi,
      Comments is something I probably would embed or maybe reference a single document that holds the embedded comments.

      Typed-collections isn’t there yet. There’s a separate project in a branch, provided by Rei, but I haven’t been able to incorporate any of that stuff yet.

      //Daniel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s