mongodbcircular-reference

why does MongoDB recommend two-way referencing? Isn't it just circular referencing?


Reference material: https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-2

db.person.findOne()
    {
        _id: ObjectID("AAF1"),
        name: "Kate Monster",
        tasks [     // array of references to Task documents
            ObjectID("ADF9"), 
            ObjectID("AE02"),
            ObjectID("AE73") 
            // etc
        ]
    }
    
db.tasks.findOne()
    {
        _id: ObjectID("ADF9"), 
        description: "Write lesson plan",
        due_date:  ISODate("2014-04-01"),
        owner: ObjectID("AAF1")     // Reference to Person document
    }

In a tutorial post from MongoDB, it specifically encourages two-way referencing. As you see, Person document references Tasks document and vice versa.

I thought it was circular referencing that should be avoided in most cases. The site didn't explain much why it's not a problem for MongoDB though. Could please someone help me understand why this is possible in MongoDB when it is such a big no no in SQL? I know it's more like a theoretical question, but I would like to implement this type of design in the database I'm working on if there is compelling reason to.


Solution

  • Its only a circular reference if you make one out of it.

    Meaning: Let's say you want to print your Mongo document to some JSON-String to print it in your browser. Instead of printing a bunch of ID's under the Tasks-Section you want to print the actual name. In this case you have to follow the ID and print the name. However: if you now go into the object and resolve the IDs behind the Owner Object, you'll be printing your Person again. This could go on indefinitely, if you program it that way. If you don't its just a bunch of IDs either way.

    EDIT: depending on your implementation, IDs are not resolved automatically and thus cause no headache.

    One thing: depending on your data structure and performance considerations, its sometimes easier to put any object directly into your parent document. Referencing the ID on both sides only makes sense in many-to-many relationship.

    HTH