mongodb - 使用字符串或 ObjectId 构造 DBRef [英] mongodb - Construct DBRef with string or ObjectId

查看:49
本文介绍了mongodb - 使用字符串或 ObjectId 构造 DBRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在 mongodb 中可以使用字符串或对象 ID 来构造 DBRef.例如

I've noticed that either a string or an object id could be used to construct a DBRef in mongodb. For example

db.persons.insert({name: 'alice'})
db.persons.find()
// { "_id" : ObjectId("5165419064fada69cef33ea2"), "name" : "alice" }
db.persons.insert({name: 'bob', sister: new DBRef('persons', '5165419064fada69cef33ea2')}) // use a string
db.persons.find()
// { "_id" : ObjectId("5165419064fada69cef33ea2"), "name" : "alice" }
// { "_id" : ObjectId("516541c064fada69cef33ea3"), "name" : "bob", "sister" : { "$ref" : "persons", "$id" : "5165419064fada69cef33ea2" } }
db.persons.insert({name: 'cavin', sister: new DBRef('persons', new ObjectId('5165419064fada69cef33ea2'))}) // use an ObjectId
db.persons.find()
// { "_id" : ObjectId("5165419064fada69cef33ea2"), "name" : "alice" }
// { "_id" : ObjectId("516541c064fada69cef33ea3"), "name" : "bob", "sister" : { "$ref" : "persons", "$id" : "5165419064fada69cef33ea2" } }
// { "_id" : ObjectId("516541e464fada69cef33ea4"), "name" : "cavin", "sister" : { "$ref" : "persons", "$id" : ObjectId("5165419064fada69cef33ea2") } }

谁能告诉我有什么区别,哪种方式更受欢迎?

Could anybody tell me what's the difference and which way is preferred?

推荐答案

唯一的区别是一个实际上是一个 ObjectId 而另一个是一个看起来像一个 的字符串表示对象 ID.

The only difference is that one is actually an ObjectId and the other is a string representation of what looks to be an ObjectId.

DBRef 作为 ObjectId:

DBRef as an ObjectId:

db.persons.insert({name: 'cavin', 
     sister: new DBRef('persons', 
         new ObjectId('5165419064fada69cef33ea2'))}) // use an ObjectId

DBRef 作为字符串:

DBRef as a String:

db.persons.insert({name: 'bob', 
     sister: new DBRef('persons', 
        '5165419064fada69cef33ea2')}) // use a string

在您包含的示例中,ObjectId 格式可以实现更高效的存储,因为它是一个 12 字节的值,而不是字符串表示所需的 24 个字节.如果您想使用 DBRefs,如果引用的集合使用 ObjectIds 作为 _id<,我将使用 ObjectId/代码>.

In the example you included, the ObjectId format could result in more efficient storage as it's a 12-byte value instead of the 24 bytes that the string representation would require. If you wanted to use DBRefs, I'd use an ObjectId if the referenced collection is using ObjectIds for the _id.

您不需要在 ObjectId>DBRef.它可以是表示相关集合/数据库的键 (_id) 的任何值.

You aren't required to use an ObjectId in a DBRef. It can be any value that represents the key (_id) of the related collection/DB.

正如 文档 所建议的,除非您有令人信服的使用理由一个 DBRef,使用手动引用代替.

As the documentation suggests, unless you have a compelling reason for using a DBRef, use manual references instead.

这篇关于mongodb - 使用字符串或 ObjectId 构造 DBRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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