Search code examples
mongodbobjectiddbref

mongodb - Construct DBRef with string or ObjectId


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?


Solution

  • 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 as an ObjectId:

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

    DBRef as a String:

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

    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.

    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.

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