Search code examples
node.jsmongodbexpresscollectionsnosql

How to store nested clause data in MongoDB


Clause formatI am just new to MOngoDB.Just want to know for the way i am using. Below is my requirement.I want to store clauses in clause collection just like below described.

SMF 1
  1.Clause 1
    a.Subcluse 1
    b.Subcluse 2
      i. Subcluse 1
        aa. Subcluse 1
        ab. Subcluse 2
        ac. Subcluse 3
      ii.Subcluse 2
  2.Cluase 2
    a.Subcluse 1
    b.Subcluse 2
      i. Subcluse 1
      ii.Subcluse 2
SMF 2

Currently i am storing clauses like this.

{
  "_id": {
    "$oid": "662f76f499ed921cf8b79025"
  },
  "smf_id": "662a5063f05d3cc77e91dce4", 
  "clause_no": 1,
  "clause_name": "Clause1", 
  "sub_clause": [
    {
      "parent_id": "662f76f499ed921cf8b79025",
      "clause_no": 1.1,
      "clause_name": "clause1.1",     
      "_id": {
        "$oid": "662f781b99ed921cf8b79031"
      },
      "sub_clause_level_2": [
        {
          "parent_id": "662f781b99ed921cf8b79031",
          "clause_no": 1.1,
          "clause_name": "clause1.1.1",        
          "_id": {
            "$oid": "662f89b5954654567da8559a"
          }
        }
      ]
    },
    {
      "parent_id": "662f76f499ed921cf8b79025",
      "clause_no": 1.2,
      "clause_name": "clause1.2",    
      "_id": {
        "$oid": "662f78e6b9148e95aeb8d455"
      },
      "sub_clause": []
    },
    {
      "parent_id": "662f76f499ed921cf8b79025",
      "clause_no": 1.3,
      "clause_name": "Clause1.3",    
      "_id": {
        "$oid": "662f791bb9148e95aeb8d45f"
      },
      "sub_clause": []
    }
  ],
  "__v": 0
}

Anyone help me to go with correct and best way.


Solution

  • This is okay as long as the sub_clause array do not exceed the document limit. Ideally, if you dont know how big the array can become, its safe to store in a separate collection (sub_clause) along with the reference (here smf_id or parentClauseId).

    For more info check https://www.mongodb.com/docs/manual/reference/limits/#:~:text=The%20maximum%20BSON%20document%20size,MongoDB%20provides%20the%20GridFS%20API.