0

Is Document References in MongoDb a recommended method or Embedded documents is the right way to do it ? My Questions comes in context of following.

class ObjectType1
{
ObjectId ID;
ObjectType2 Type2Element;
}

class ObjectType2
{
ObjectId ID;
}

I understand we could use MongoDBRef to reference ObjectType2 element in first class, but i wasn't able to locate FetchDBRefAs method (am using official mongodb C# driver, may be am looking at wrong place/namespace).

What is recommended way to link entities if required in MongoDb, especially working with C# ? Thanks

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • *"I understand we could use MongoDBRef"* I don't know where you read that, but it must be an old source or a very ill informed one. Don't use `DBRef`. If you want to reference, then use plain `ObjectId` values in preference or whatever for your local and foreign keys and instead define the models they point to "in your application logic instead". `DBRef` is as close to a deprecated concept as you get without an official deprecation notice. It is not supported by many modern operations and is a general hindrance to queries. – Neil Lunn Aug 18 '17 at 06:39
  • The choice of "Embed vs Reference" is really opinion based and the only real solution is entirely based on your actual application usage patterns and requirements and should not be swayed in any way by peoples opinions on the subject. To get a better understanding of why you use "one or the other" you should rather read and understand existing references such as [MongoDB relationships: embed or reference?](https://stackoverflow.com/q/5373198/2313887) or [Mongoose populate vs object nesting](https://stackoverflow.com/q/24096546/2313887). The latter still be basically relevant to the intent – Neil Lunn Aug 18 '17 at 06:42
  • Thanks @NeilLunn – Anu Viswan Aug 18 '17 at 06:59
  • @NeilLunn If you do not mind, could you pls educate me on ill-effects of DbRef ? – Anu Viswan Aug 18 '17 at 07:25

1 Answers1

1

To answer your question shortly: Depends on your use case.

Some rules I like to follow when I design my own db schema:

  • If in your code you need both ObjectType1 and ObjectType2 at the same time then I suggest you use embedded approach because you need only 1 query to perform CRUD on them. Furthermore, it is more logical because all info you need is at the same place in db.

  • If most of times in code you need only ObjectType2, then I would separate them in 2 collections.

This part of official docs has lots more info: https://docs.mongodb.com/manual/core/data-modeling-introduction/

BOR4
  • 610
  • 4
  • 9
  • Do you recommend MongoDBRef or you would go using ObjectId when the documetns are separated ? – Anu Viswan Aug 18 '17 at 10:17
  • When I was learning Mongo I came to this post. https://stackoverflow.com/questions/9412341/mongodb-is-dbref-necessary. Made me never use DBRef as it seems lot's of people say it should be avoided. – BOR4 Aug 18 '17 at 10:31