user3566578
user3566578

Reputation: 61

How to store dynamic fields in Mongo DB

I am new to MongoDB, but am looking at it to solve this problem:

My application has a dynamic form builder that lets users add dynamic fields on the form . None of the field on the form is fix or static.

User can add any number and any type of fields like text field , Dropdown or date fields on the form and save the form .

I believe since its a dynamic storage and fields are not static, Oracle DB wont work for storage . Can Mongo DB be used for such storage and fetching the data ?

How the data be stored in Mongo DB and fetched to display the form.

Thanks in advance !

Upvotes: 6

Views: 13096

Answers (2)

Philipp
Philipp

Reputation: 69663

Yes, MongoDB can do this. A document to represent such a form could look like this:

{
     tile: "A simple customer survey",
     creator: "Philipp",
     created: ISODate("2014-04-24T16:59:42.389Z"),
     questions: [
         { 
           question: "How old are you?",
           input: "number"
         },
         { 
           question: "Do you like our products?",
           answers: [
               "Yes",
               "No",
               "Maybe"
           ]
         },
         { 
           question: "Which aspects of our products do you like?",
           multiple: true,
           answers: [
               "color",
               "shape",
               "material",
               "price",
               "does not explode often"
           ]
         }
     ]
}

Note that the entries in the "questions" array all have a different combination of fields. Handling this is no problem at all for MongoDB because it does not enforce a consistent schema for the documents in a collection.

Upvotes: 2

sir4ju1
sir4ju1

Reputation: 543

MongoDb is Document based Database as you mentioned it has no column or field restriction. You can put your dynamic field into a object and save it to same collection.

for example

 Person: {
   name: '',
   Contacts: [ contact 1, contact 2]
}

you can add more field too for example you can add email to it

 Person: 
 { name: '', contacts: [], email: ''}

You can now save that in Person Collection as well. Just use javascript object and add new key and value and save it.

 person.email = 'new value';

When Fetching those you can iterate over keys on the objects and show the values again to front end

for (var key in person) {
  // do something with key
}

Upvotes: 4

Related Questions