bonez
bonez

Reputation: 695

MongoDB flexible data structure

I'm just starting to learn Mongo DB.

I chose it for my current project because I need a fairly flexible schema, based on user inputs.

In mySql I had a table to store data entered by the user that looked like

ID      Key         Value
--------------------------
1      Color        Black
2      Color        White
3      Lace_length   12 

Which i think is fairly typical of storing user entered data that could be anything

My question is what is the best way to represent this in MongoDB

My thought is something like this

{ _id: ObjectId{} ,
   options: [
         { colors: [ { black, white , ... } ] ,

          lace_length: [ { 12, 13 , 14 } ] } 
         ]
}

Does this seem like a sensible way to store flexible 'column names' based on various user input or is there a better way to handle this?

Thanks

Upvotes: 0

Views: 452

Answers (1)

paulmelnikow
paulmelnikow

Reputation: 17208

I can't say I fully understand your SQL example. Is there a foreign key, something which corresponds with the object id?

If your options are many-to-many, I'd set it up like this:

{ _id: ObjectId() ,
  options: {
      colors: [ black, white , ... ],
      lace_length: [ 12, 13, 14 ]
  }
}

If some options have only one value, then like this:

{ _id: ObjectId() ,
  options: {
      colors: [ black, white , ... ],
      lace_length: [ 12, 13, 14 ],
      upc: 1234567890
  }
}

Upvotes: 1

Related Questions