views:

41

answers:

1

I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself.

{$ref:'user', $id:'10285102912A', username:'Soviut'}

For example, I may want to have the username available even though the user document is referenced. This would provide me all the benefits of a single document approach; Faster querying and eliminating the need to do manual dereferencing in my code. While at the same time allowing me to use references where they make sense.

The idea being that when the referenced document is updated (a user changes their name, for example) my business layer can automatically update all the documents that reference it.

Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs? Will it break anything? Will I lose my data each time a reference is rewritten? Will drivers like pymongo support it?

+1  A: 

Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs?

It might be cleaner to have separate "cached" and "ref" fields... it depends one what your data is like.

Will I lose my data each time a reference is rewritten?

You could, but not if you're careful. If you're updating the DB ref subobject, just make sure you're updating the specific fields you want updated, not overwriting the whole subobject.

Remember that references as they are just normal objects. The database reference is a standard, not a special type.

Will drivers like pymongo support it?

The driver's dereferencing helpers will still work. The helpers just do a findOne with the $ref and $id fields.

kristina
Thanks Kristina. I'm confident enough to at least attempt this on my first pass then. Regarding cached fields, is there any popular format for this? Maybe author vs cache_author or something?
Soviut
Also, as a side note, your blog posts are excellent. They really helped me get up to speed on Mongo quickly.
Soviut
Thanks! There isn't any standard that I know of, sorry. cache_whatever sounds good.
kristina