0

In my project, it has 3 models:

  1. City
  2. Plaza
  3. Store

a city has plazas and stores; a plaza has stores.

My initial design is to use "foreign keys" for the relationship. (I am from mysql and jsut start to pick up mongodb)

class City(Document):
     name = StringField()

class Plaza(Document):
     name = StringField()
     city = ObjectIdField()

class Store(Document):
     name = StringField()
     city = ObjectIDField()
     plaza = ObjectIdField()

I feel this design is quite like a sql approach.

The scope of the project is like this: 5 cities; each city has 5 plazas; a plaza has 200 stores. a store has a number of products(haven't been modeled in above code)

I will query all stores in a city or in a plaza; all plazas in a city.

Should I embed all stores and plazas in City collection? I have heard do not use reference in mongodb, use embeded documents instead. In my specific projects, which one is a better approach? For me, I am comfortable with the "foreign key" design but am afraid of not taking advantage of mongodb.

shoujs
  • 1,113
  • 1
  • 11
  • 24

2 Answers2

0

From the way you described your project, it seems like an embedded approach is probably not needed - if you use indices on the city and plaza you can perform the queries you mentioned very quickly. Embedding tends to be more helpful for caching or when the embedded data doesn't make much sense on its own, and always is accessed at the same time as the parent data - not really the case here, something like addresses are a good example.

gregs
  • 126
  • 2
0

I think it makes sense to have a single collection of stores.

In each store document you could have an attribute called city, you could also have an attribute plaza. There are many other ways to structure its attributes, including more complex (subdocument) values.

If your document is:

{ storeName:  "Books and Coffee",
  location:   "plaza 17",
  city:       "Anytown",
}

You can easily query for all stores in Anytown with

db.stores.find({"city":"Anytown"})

It doesn't make sense to store city and plaza in separate collections because then you will have to do multiple queries every time you need information that spans more than one collection, like store and the city it's in, or all stores in city "X".

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133