0

I have a one to many relationship between "region" and "story" collections. I.e. each region has multiple stories. The story collection contains every story for every region with a "regionId" key that identifies what region that story belongs to. I am going to need to lookup stories associated with various regionIds, presumably using Story.find{"regionId" : <regionId>} In the future there could be thousands or millions of total stories and am aware doing a collection search would be very inefficient. Initially I made a "stories" field in "regions" so I could lookup by _id but I realized that would create a reference nightmare. My question is, can I just index the "regionId" field to accomplish what I want, even though there are multiple documents with the same regionId?

storySchema.createIndex{ { regionId: 1  } }
Matthew Kline
  • 71
  • 1
  • 6

1 Answers1

0

You should checkout mongoDB aggregations. You would do something like:

Story.aggregation([
 {
  $match: {
    region: regionId
    }
 }
])
Valiant
  • 88
  • 1
  • 10
  • Do you think I should just scrap the Story collection and store them in subdocuments of Region? I would've thought that that would create memory problems since the docs would be huge but I guess that's good practice according to this: https://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference – Matthew Kline Jul 14 '21 at 20:18
  • I think it is a better practice to keep the data in separate collections, and reference it instead. You can check this: https://web.archive.org/web/20110111033238/http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference to get a better understanding for your use case – Valiant Jul 14 '21 at 20:23