Tasks and subtasks

Hi all, I’m new to Mongo and I have to figure out something before selecting it as the right tool.
I need to store a list of tasks, and each one can contain other tasks. Moreover at a certain point in the development we will introduce a layer above which means all the parent tasks will become children tasks of others.
How can this be implemented and it is a good idea?
The alternatives I’m thinking of are:

  • write each subtask inside a list property of their parent task, but then I will be stuck when need an above layer
  • treat all tasks as same and reference the parent with an Id (like I would do in a SQL db), and for this case I don’t know how easy is to query and update everything

Thanks in advance

Hi @Simone_Cremasco ,

The cool thing about MongoDB is its flexible schema and the ability to use an outlier pattern for some extreme use cases in your app.

In general the relationship needs to be formed as embedding if the data needs to be queried together to form a single view in your application. So if the app need to show all the tasks and subtask titles for a specific user it makes sense to store them all in a single document as long as you are not hiting a known antipattern like unbounded arrays:

_ id : ...,
taskId : "xxx", 
name : "task1" ,
type : "root"
subtasks : [ { taskId : "yyy", 
                     name : "subtask1" ,
                    type : "subtask"} ...

Now in case you need to change your schema later you can go any of the following ways:

  • Take the entire root task and push it as a subtask in a new replaced document
  • Add a new root document pointing to this document in its taskid. This will require you to add an extra logic to lookup or add a query to fetch the nested documents.

What I am trying to say is that the flexible schema can allow you to create a hybrid solution where your system knows how to treat both design pattern and use them when you need to.


Hello @Simone_Cremasco, welcome to the MongoDB Community forum!

One of the the design ideas is the Model Tree Structures. It says:

MongoDB allows various ways to use tree data structures to model large hierarchical or nested data relationships. …

The above linked data modeling documentation has various ways of structuring your data based upon your usage requirements, and then querying it. In addition to the MongoDB Query Language methods, $graphLookup is an aggregation stage which can be used for querying this kind of data.

1 Like

Thank you so much, I will study that