Question

Let's say I want to model my domain using the composite pattern. The model (gist) is fairly simple. At album controller I want to perform a search on a given name:

public ActionResult Edit(String name) {
    if(name == null) {
        ViewBag.ViewRoot = true;
        return View(this.albums.All());
    }

    var album = this.albums.Single(a => a.Name == name);
    if(album != null) {
        ViewBag.ViewRoot = false;
        return View(album.Yield());
    }

    return View("404", (Object)("Album:" + name));
}

The resulting (filtered) persisted object looks like this:

{
    "_id" : "52ab1a6a7b88c91e5cfc39ff",
    "ParentId" : null,
    "Name" : "sample01",
    "Items" : [{
        "_t" : "Album",
        "_id" : null,
        "ParentId" : "52ab1a6a7b88c91e5cfc39ff",
        "Name" : "sample02",
        "Items" : [{
            "_t" : "Album",
            "_id" : null,
            "ParentId" : null,
            "Name" : "sample03",
            "Items" : []
        }]
    }]
}

Mongodb doesn't perform recursive search out of the box. But it allows you to perform queries given that you provide an explicit direction (code sample is taken from MongoDB + C# driver + query array of elements where each array element contains sub-document to query on):

Query.ElemMatch("Children", Query.And(Query.EQ("StatusId", 1), Query.EQ("Active", true),Query.LT("SubChild.ExpiresOn", DateTime.UtcNow)));

I've been thinking about two solutions (which might keep it composite):

  • tracking the node depth (then I should build complicated query);
  • use parent sign (id, name), fetch entire graph, then perform recursive search at the client side.

What are your thoughts on this?

Was it helpful?

Solution

There are some design patterns for modelling tree structures in mongodb among them being :

  • Parent References
  • Child References
  • Array of Ancestors
  • Materialised Paths
  • Nested Sets

for me it sounds like you need a tree structure with materialised paths, but you can have a look at MongoDB documentation for further information about the available design patterns used for similar issues

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top