0

In mongodb, which style is better? 1) or 2)? Can I retrieve only line name from 1) despite of getting whole record on db.record.find("line":"east")?

1.

{
  "line": "east",
  "station":[
    { "name": "ABC", "_id": "1", },
    { "name": "DEF", "_id": "2" }
  ]
}

2.

{ "line": "east", "l_id":"1"},
{"station":"ABC", "_id":"1", "l_id":"1"},
{"station":"ABC", "_id":"2", "l_id":"1"}

Note: line and station has one to many relationship.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
anonymous255
  • 108
  • 10
  • 1
    Possible duplicate of [MongoDB relationships: embed or reference?](http://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference) – joao Mar 02 '16 at 18:34

1 Answers1

0

If you are most commonly getting stations by line and often need all stations of a line alt 1 is the best. If you are commonly retrieving single stations or a subset of stations 2 is the best. Alt 2 can lead to more queries since mongo doesn't really have any relations, alt 1 can lead to larger reads and make it more difficult to keep the working set in RAM because of larger objects. Alt 1 also has a minor drawback if you change values in a station on multiple lines - then you have to update its instance in each of the line documents containg it.

To get a partial object, i.e. not all stations in alt 1, you can do a projection to filter out what you don't want. It still means reading the whole object into memory first so you wouldn't gain a lot in performance from doing that.

Anders Bornholm
  • 1,326
  • 7
  • 18
  • With an index on `l_id`, `db.record.find({"l_id": "1"})` is hardly less efficient than `db.record.findOne({"_id": 1"})`, even at the micro-optimization level. Beyond that, it has no chance of inconsistency compared to the first one, so I don't really agree with your first sentence. Personally, I've seen very few use-cases for embedded documents. But to each their own on an opinion question. – chrisbajorin Mar 02 '16 at 19:48