Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can DBRefs contain additional fields?

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?

like image 311
Soviut Avatar asked May 23 '10 23:05

Soviut


1 Answers

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.

like image 139
kristina Avatar answered Sep 22 '22 01:09

kristina