Is it better to save id of a document in another document as ObjectId or String

Storing it as objectId is benificial. It is faster as ObjectId size is 12 bytes compared to string which takes 24 bytes.

Also, You should try to de-normalize your collections so that you don't need to make 2 collections (Opposite to RDBMS).

Something like this might be better in general:

{ _id : "1",
  person : { 
             Name : "abc",
             age: 20
           },
  address : { 
             street : "1st main",
             city: "Bangalore",
             country: "India"
            }
}

But again, it depends on your use case. This might be not suitable sometimes.

Hope that helps! :)


As for use string as id of document, in meteor collection, you could generate the document id either Random.id() as string or Meteor.Collection.ObjectID() as ObjectId.

In this discussion loop, Mongodb string id vs ObjectId, here is one good summary,

ObjectId Pros

  • it has an embedded timestamp in it.
  • it's the default Mongo _id type; ubiquitous
  • interoperability with other apps and drivers

ObjectId Cons

  • it's an object, and a little more difficult to manipulate in practice.
  • there will be times when you forget to wrap your string in new ObjectId()
  • it requires server side object creation to maintain _id uniqueness - which makes generating them client-side by minimongo problematic

String Pros

  • developers can create domain specific _id topologies

String Cons

  • developer has to ensure uniqueness of _ids
  • findAndModify() and getNextSequence() queries may be invalidated

All those information above is based on the meteor framework. For Mongodb, it is better to use ObjectId, reasons are in the question linked in your question.


Regardless of performance, you should store the "referential key" in the same format as the _id field that you are referring too. That means that if your referred document is:

{ _id: ObjectID("68746287..."), value: 'foo' }

then you'd refer to it as:

{ _id: ObjectID(…parent document id…), subDoc: ObjectID("68746287...")

If the document that you're pointing to has a string as an ID, then it'd look like:

{ _id: "derick-address-1", value: 'foo' }

then you'd refer to it as:

{ _id: ObjectID(…parent document id…), subDoc: "derick-address-1" }

Besides that, because you're talking about persons and addresses, it might make more sense to not have them in two documents altogether, but instead embed the document:

{ _id: ObjectID(…parent document id…),
  'name' : 'Derick',
  'addresses' : [
     { 'type' : 'Home', 'street' : 'Victoria Road' },
     { 'type' : 'Work', 'street' : 'King William Street' },
  ]
}

Tags:

Mongodb