5

When should I use the aggregation pipeline?

Scenerio: I have some mongo db documents like this

`

    {
    id:"",
    text:"",
    dept:"",
    group:"",
    parent:"",
    }

`

Now I need to prepare a tree structure out of it using the parent field.

`

    tree:[
    {
    id:"",
    text:"",
    dept:"",
    group:"",
    parent:"",
    children:[
       {
         id:"",
         text:"",
         dept:"",
         group:"",
         parent:"",
    }]
    },{
    id:"",
    text:"",
    dept:"",
    group:"",
    parent:"",
    }]

`

Now this structure could be heavily nested. As much of my knowledge I can write a aggregation pipeline for making this structure. but the question is this structure will be prepared frequently like on each refresh of the page. Should we use the pipeline or we should store the json documents in the tree structure as it is.

Yashdeep Hinge
  • 382
  • 2
  • 14

1 Answers1

3

The advantage that Mongo brings into picture is its NoSQL schema-less structure. You need to make use of it and not store data in a relational model.

Hence when you are aware that you need to fetch a lot of nested data, it is advisable to model your database in such a way, that you store all the nested data in a single document. As a result, when you do a fetch, you need not do any additional computation on it.

For more information on the same, refer this.

  • but what yeah I got you but what if there is no situation where I need all the nested data at the ui but only one record and I always the key of it. Than in mongo's words we won't be joining data at neither the db side nor the backend side. – Yashdeep Hinge Jul 26 '18 at 07:31
  • 2
    Just because you are storing data in a heavily nested structure, doesn't mean you need to provide each and every field back to UI. If there are 50 attributes that are being stored, but only 5 of them being used by UI, you need to use `$project` to get only those 5 attributes. Hence as per your original question, you should prefer a nested document structure. – Subhashree Pradhan Jul 26 '18 at 08:56
  • What about when you have repetition of data that may change in the future? Is it still advisable to keep all data related to a document nested in the document? As a dumb example - say a person object, tha contains a house object, that has a list of rooms, and in each room there's a list of electronics with fields -make, model, etc... and a 'make' is wrong in some of those objects. I'll have to update the make value in every document. Is that the way it is intended to be used? – mal Sep 24 '22 at 06:40