MongoDb: Benefit of using ObjectID vs a string containing an Id?

前端 未结 3 1937
小蘑菇
小蘑菇 2020-12-09 09:42

Is there any benefit to storing an id to a related document as an ObjectId versus storing it as a string literal?

Using ObjectID:

{
   \"_id\": Objec         


        
3条回答
  •  一个人的身影
    2020-12-09 09:49

    The biggest reason is that ObjectIDs are 12 bytes, whereas an equivalent string is 24 bytes. Over a large enough collection, those 12 bytes saved per ID really add up! Those IDs also mean fewer bytes transferred over the wire when reading or writing the document, as well.

    Additionally, some ODMs expect ObjectIDs for external document references, and may be confused by string versions of the ID. I am not familiar enough with PHP ODMs to say if this might affect you specifically, though.

    Regarding the API stuff, though, you should probably be doing normalization of the data before sending it to the client anyhow, because since Mongo doesn't enforce a schema, you can have literally any sort of data in a given field, so you might have some documents that have string IDs, and others that have BSON IDs, and your API would happily send them both through to the client, but one or the other might cause breakage. In this particular case, you should use BSON ObjectIDs in your documents, and then should cast them to strings in your API output.

提交回复
热议问题