Robert
Robert

Reputation: 368

MongoDB - DBRef to a DBObject

Using Java ... not that it matters.

Having a problem and maybe it is just a design issue.

I assign "_id" field to all of my documents, even embedded ones. I have a parent document ( and the collection for those ) which has an embedded document

So I have something like:

{ "_id" : "49902cde5162504500b45c2c" , 
  "name" : "MongoDB" , 
  "type" : "database" , 
  "count" : 1 , 
  "info" : { "_id" : "49902cde5162504500b45c2y", 
             "x" : 203 , 
             "y" : 102
           }
}

Now I want to have another document which references my "info" via a DBRef, don't want a copy. So, I create a DBRef which points to the collection of the parent document and specifies the _id as xxxx5c2y. However, calling fetch() on the DBRef gives a NULL.

Does it mean that DBRef and fetch() only works on top level collection entry "_id" fields?

I would have expected that fetch() would consume all keys:values within the braces of the document .. but maybe that is asking too much. Does anyone know?? Is there no way to create cross document references except at the top level?

Thanks

Upvotes: 0

Views: 2668

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39277

Yes, your DBRef _id references need to be to documents in your collection, not to embedded documents.

If you want to find the embedded document you'll need to do a query on info._id and you'll need to add an index on that too (for performance) OR you'll need to store that embedded document in a collection and treat the embedded one as a copy. Copying is OK in MongoDB ... 'one fact one place' doesn't apply here ... provided you have some way to update the copy when the main one changes (eventual consistency).

BTW, on DBRef's, the official guidance says "Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient."

Also, why do you want to reference info within a document? If it was an array I could understand why you might want to refer to individual entries but since it doesn't appear to be an array in your example, why not just refer to the containing document by its _id?

Upvotes: 1

Related Questions