Skip to content Skip to sidebar Skip to footer

Syntax For Linking Documents In Mongodb

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 int

Solution 1:

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.

Solution 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"}}

Post a Comment for "Syntax For Linking Documents In Mongodb"