问题
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.
回答1:
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"}}
回答2:
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.
来源:https://stackoverflow.com/questions/11471633/syntax-for-linking-documents-in-mongodb