1

If I have two objects in a user collection:

{_id: 1, name: 'foo', workItems: []}
{_id: 2, name: 'bar', workItems: []}

how would I add links to objects in a workItem collection into the workItems array for each user?

I understand direct embedding but some workItems will be assigned to multiple users so I don't want to duplicate data. I have looked on mongodb.org but I can't find any examples of linking.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
Daniel Robinson
  • 13,806
  • 18
  • 64
  • 112

2 Answers2

3

Sometimes it is just better to duplicate the data. MongoDB is a non relational Database. Some ways of doing stuffs are bad practices with relational databases but intended with non relational one. This really is not the same way of thinking even though there are obvious common points.

At my work, we use it in production and found it both easier and faster for read operations to duplicate the data. This is precisely where the power of MongoDB stands. Of course, when a workitem is modified, this requires your application to update all the places where it appears... This may not be a good solution for systems that are write intensive.

Another point is that joints are not handled by the engine so that you will have to issue at least a second request. You will then have to do the joint manually on the application side. Either way, you will have to move logic from the database to the client application.

yadutaf
  • 6,840
  • 1
  • 37
  • 48
2

You can do a DBRef like this:

{ $ref : <name of collection where reference is>, $id : <_id of document>, $db : <optional argument for specifying the databse the document is at> }

So your document would look like this:

{_id: 1, name: 'foo', workItems: {$ref: "blarg", $id: "1"}}
Randall Hunt
  • 12,132
  • 6
  • 32
  • 42
  • 1
    alternatively, you could just store the _ids or some other unique identifier of each workItem in the array - the linking can be "logical". – Asya Kamsky Jul 13 '12 at 19:13
  • Exactly, to clarify Aysa's answer you can just make multiple queries. – Randall Hunt Jul 13 '12 at 19:48
  • 1
    as jtlebi says - you have to make two queries regardless, you may as well make it readable. – Asya Kamsky Jul 14 '12 at 02:30
  • thanks, that was what I was looking for, it makes sense, I was trying to think of some 'magical' way that the data was linked rather than just specifying the collection and doc _id. Thanks to the other comments and jtlebi for your answer, it was a good answer also. – Daniel Robinson Jul 14 '12 at 19:27