3
votes

I'm confused, what is the best format for the following case:

Name: Pretty nice hot dog
Stock: 10
Weight: 0.1 grams
Price: 2 dollars

Name: An ordinary dumbbell
Stock: 5
Weight: 4 kilograms
Price: 667.98 yens

This:

db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : "gram"}, "price" : {"value" : 2, "unit" : "dollar"}})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : "kilogram"}, "price" : {"value" : 667.98, "unit" : "yen"}})

Or this:

db.unit.save ({"_id" : 1, "name" : "dollar"})
db.unit.save ({"_id" : 2, "name" : "yen"})
db.unit.save ({"_id" : 4, "name" : "gram"})
db.unit.save ({"_id" : 5, "name" : "kilogram"})

db.item.save ({"_id" : 1, "name" : "Pretty nice hot dog", "stock" : 10, "weight" : {"value" : 0.1, "unit" : [new DBRef ("unit", 4)]}, "price" : [new DBRef ("unit", 1)]})
db.item.save ({"_id" : 2, "name" : "An ordinary dumbbell", "stock" : 5, "weight" : {"value" : 4, "unit" : [new DBRef ("unit", 5)]}, "price" : [new DBRef ("unit", 2)]})

The values of the field "unit" is immutable, I don't know if I should put it in a separate collection.

Thanks

2

2 Answers

4
votes

Read Schema Design from MongoDb docs. This is exactly your case.

3
votes

I'd say no. Unless you need the flexibility to query from the units (all items with a certain cost), I wouldn't. And if you need to, you can always use map reduce to get all items of a certain cost later on.