MongoDB objectsId

I have one collection, with document id set as MongoDb object identifiers (therefore they appear in db as:

Collection1 "someId": { "$oid": "5003cb802e28076412000001" }, 

In another collection, I refer to them. However, sometimes these links are apparently stored as regular veins:

 Collection 2 "someForiegnId": { "$oid": "5003cb802e28076412000001" }, 

But in other cases, they turned it into db like a regular string.

 Collection 2 "someForiegnId": "5003cb802e28076412000001", 

My question is - Is it important to store these external links in oid format, or can they just be strings?

+6
source share
1 answer

I know that I answer for one year, but still.

It is always advisable to be consistent in your database. No matter how you store your data (for example, the IP address in the form of the string "87.123.12.12" array [87, 123, 12, 12] or the number 1467681804 ), it should always be the same. The same with your data: you need to choose one format and stick to it.

The format you choose will have consequences for how much storage you will use and how quickly you can request data. And the best way is to save them as ObjectID for the following reasons:

  • it only takes 12 bytes to store the objectID , whereas you need twice to keep the same in the string. Of course, this is a small difference, but it is absolutely free. Also, in a world where you are trying to put all of your data into memory (or at least as much as possible), this is a good consideration. Thus, you save not only the hard drive, but also RAM.
  • you can easily get the timestamp from your id. It is sometimes useful to get when an object has been created. Using strings you cannot do this.
  • if you decide to create an index based on this field - its size will be much smaller, and you will query it much faster (because it is a number), and then query by line.

So, even if I had only string representations - I would switch to ObjectID (), in your case it will certainly switch worse (I know that you probably already did this).

PS You can change the field by changing the request in the next answer .

+3
source

Source: https://habr.com/ru/post/922039/


All Articles