I have a webapp where I’m created an embedded document for educations. The job document looks something like this:
"educations" : [
{
"school" : "Brandywine High School",
"major" : "Testingasdf",
"grad_year" : ISODate("1979-01-01T00:00:00Z"),
"school_type" : "Graduate",
"_id" : ObjectId("4fb26c9ce5be08208b000ce4")
}
],
"email" : "user@domain.com",
The education hash has the details of the job. I noticed that if i create the hash without an ID:
User.collection.update(
{ _id: @user.id },
{ :$push => { educations: education } },
{ safe: true }
)
and I query the education from the Rails console, the ID will change each time:
irb(main):004:0> User.brandon.educations.map(&:id)
=> [BSON::ObjectId('4fb26e13e5be082384000007')]
irb(main):005:0> User.brandon.educations.map(&:id)
=> [BSON::ObjectId('4fb26e13e5be082384000009')]
However, if I do this:
User.collection.update(
{ _id: @user.id },
{ :$push => { educations: BSON::ObjectId.create_pk(education) } },
{ safe: true }
)
The ID is the same each time queried from the console. Because of this, I’m having trouble referencing the education to edit the embedded doc in the browser.
Do I always have to supply a BSON ID when I create an embedded document?
If you don’t supply some kind of identifier (it could be a String, an int, etc) in the _id field, then MongoDB will automatically create one for you, to make the document unique (so that it can be looked up by _id). There is normally a unique index on _id, so if the document isn’t unique, insertion will fail (or the existing document will be updated instead, etc).
MongoDB’s strategy for making the document unique is to use an ObjectID, as these are globally unique. They are also different every time you create one — that’s how they are globally unique.
Long story short: if you have a key that makes your document 100% unique already (possibly :school in your example), then store it as _id, and MongoDB will do the hard work for you.