0

I have a database structure whose documents use a foreign key for referencing each other. Even though MongoDB don't do very well at JOIN query, we can get the documents by running separate queries based on the foreign Key.

I can use MongoDB's ObjectID (_id) which is unique. But it's too long and also displaying this long id at client side for querying data looks little ugly. I thought of creating custom Auto-Incrementing in MongoDB which will solve the issue but MongoDB documentation says:

Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with large numbers of documents.

So what's the best solution for my below data structure

Collection: Products
{ 
    Project_ID: 1001, <Auto Incrementing>
    Product: "Example Product",
    ..<Few other fields>..
}


Collection: Payments
{ 
    Project_ID: 1001, <Foreign key>
    Pay_ID: 2001,  <Auto Incrementing>
    ..<Few other fields>..
}


Collection: Others
{ 
    Project_ID: 1001, <Foreign key>
    Pay_ID: 2001,  <Foreign key>
    Other_ID: 3001,  <Auto Incrementing>
    ..<Few other fields>..
}
Community
  • 1
  • 1
sravis
  • 3,562
  • 6
  • 36
  • 73
  • 1
    It is rare to display `_id` to client, right? You can always hide the `_id` by using `POST` request. – Raptor Dec 19 '14 at 04:07
  • Erm, and about every display technology allows to enumerate table lines and such. To make a long story short for the OP: there is no autoincrement. – Markus W Mahlberg Dec 19 '14 at 06:43
  • 1
    @OP: I have the feeling that what you are trying is to do (knowingly or subconscious) is to use MongoDB as an RDBMS. There is no notion of a foreign key in MongoDB, there is no autoincrement. If you try to emulate a RDBMS with MongoDB, here is what will happen: you end up with an overnormalized, underperforming system with a bloated code base. The whole process of development is different from the start. In RDBMS, you resemble your domain model structure and try to get your questions answered. In MongoDB, you create your models according to the questions you want answered. – Markus W Mahlberg Dec 19 '14 at 06:57

1 Answers1

0

MongoDB is not meant to be used like a Relational Database. It does not support the concept of Foreign Key on the server side. Ideally you have to embed the child documents. For more info refer this post

MongoDB normalization, foreign key and joining

Community
  • 1
  • 1