通过字符串而不是ObjectId引用其他文档 [英] Referencing Other Documents by String rather than ObjectId

查看:55
本文介绍了通过字符串而不是ObjectId引用其他文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个收藏夹:

ProductsCategories.

后一个集合的文档有2个字段:

The latter collection's documents have 2 fields:

  • _id(BSON ObjectId)
  • 名称(字符串)

后一个集合的文档包含3个字段:

The latter collection's documents have 3 fields:

  • _id(BSON ObjectId)
  • 名称(字符串)
  • 产品(字符串数组)

假设我有以下Product文档:

{ "_id" : ObjectId("AAA"), "name" : "Shovel" }

假设我有以下Category文档:

{ "_id" : ObjectId("BBB"), "Name" : "Gardening", "Products" : ["AAA"] }

出于本示例的目的,假定AAABBB是合法的ObjectId,例如:ObjectId("523c7df5c30cc960b235ddee"),它们将等于内部ObjectId的字符串.

For purposes of this example, assume that AAA and BBB are legitimate ObjectId's - example: ObjectId("523c7df5c30cc960b235ddee") where they would equal the inner ObjectId's string.

Products字段应存储为ObjectId(...)而不是字符串存储吗?

Should the Products field be stored as ObjectId(...)'s rather than as Strings?

推荐答案

只要您始终使用同一类型(以便正确进行比较),区别就是:

As long as you consistently use the same type (so that comparisons happen correctly), the difference is:

  1. 不能将ObjectId与具有相同ObjectId值的String表示形式进行比较.因此,ObjectId("523c7df5c30cc960b235ddee")不等于"523c7df5c30cc960b235ddee".
  2. ObjectId s在本地存储时将存储为12个字节,外加字段名
  3. ObjectId作为字符串存储时,通常以24个字节存储(因为它将转换为十六进制数字),加上字段名
  4. 使用12个字节的数字可以使比较效率更高,因为它比较的是更少的字节.不过,对于大多数使用类型而言,这并不重要,因此它是一种微优化(但是您应该知道一些事情)
  5. 奖金-如果您不使用简短的缩写字段名,那么本机使用ObjectId作为12个字节的大小好处就没关系了,因为当存储为时,字段名将远远超过字节的大小一个字符串.
  1. An ObjectId cannot be compared to a String representation of the same ObjectId value. Thus, ObjectId("523c7df5c30cc960b235ddee") is not equal to "523c7df5c30cc960b235ddee".
  2. ObjectIds, when stored natively, will be stored as 12 bytes, plus field name
  3. An ObjectId, when stored as a string, will be commonly stored in 24 bytes (as it will be converted to a hexadecimal number), plus field name
  4. Comparisons can be made more SLIGHTLY more efficiently with the 12 byte number, as it's comparing fewer bytes. It won't matter in most types of usage though, so it's a micro-optimization (but something you should know)
  5. Bonus -- if you don't use short abbreviated field names, the size benefit of using an ObjectId natively as 12 bytes really won't matter, as the field names will far outweigh the size of bytes when stored as a string.

我建议将它们存储为本机ObjectId.某些驱动程序可以有选择地且透明地转换为ObjectIdString并返回,以便客户端代码可以更轻松地对其进行操作.例如,C#驱动程序可以做到这一点,而我已经使用它,以便在序列化为JSON时,ObjectId的格式很简单,很容易在JavaScript中使用.

I'd recommend storing them as native ObjectIds. Some drivers can optionally and transparently translate to an ObjectId to a String and back so that the client code can more easily manipulate it. The C# driver for example can do this, and I've used it so that when serializing to JSON, the ObjectId is in a simple format that is easily consumed in JavaScript.

这篇关于通过字符串而不是ObjectId引用其他文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆