mongodb-odm icon indicating copy to clipboard operation
mongodb-odm copied to clipboard

Inline field denormalization for Reference* mapping

Open j opened this issue 11 years ago • 6 comments

Think of the following two documents:

<?php

/** @Document() */
class Survey {
    /** @Id() */
    public $id;

    /** @ReferenceMany(targetDocument="Question", embedFields={"question"}) */
    public $questions;
}

/** @Document() */
class Question {
    /** @Id() */
    public $id;

    /** @String() */
    public $question;
}

The mongo stored documents for surveys would look like:

{
    "_id": "...",
    "questions": [
        { "$ref": "...", "$id": "...", "$db": "...", "question": "Is ODM awesome?" },
        { "$ref": "...", "$id": "...", "$db": "...", "question": "Isn't this such a great feature?!" },
    ]
}

So that if you do the following, no extra finds will be triggered unless the field wasn't embedded in the referenced document data:

<?php

$questions = [];
foreach ($surveyRepository->find("...")->getQuestions() as $question) {
    $questions[$question->getId()] = $question->getQuestion();
}

Updates to the question may cascade unless configured to not do so, or the other way around. In most of my cases, a cascade can occur.. but if someone happens to use this feature on an active database with many records, then shit can hit the fan!

It'd be easy to create a document and manage it as if it were it's own document and just associate that to one thing and be embedded. I tend to use it this way in many cases... thus would limit many finds.

Another thing that can also solve this problem is to introduce caching, but that's another topic.

j avatar Jun 10 '13 19:06 j

I have implemented this for a long time for sharding: see #325 generally it makes the same what you explain here, but it's incomplete and need some rewrites to fit upstream.

tecbot avatar Jun 10 '13 19:06 tecbot

As mentioned by @tecbot, this makes sense when using a sharded setup. I'll be revisiting this once #1349 is finished (since that involves some changes to the DBRef logic used by ODM)

alcaeus avatar Mar 14 '16 15:03 alcaeus

I've started working on this a while ago (see #1527), but this won't make much sense until we've got the new array update operators that allow us to keep the data in sync (if the user so wishes).

alcaeus avatar Dec 22 '17 06:12 alcaeus

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in a week if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 06 '21 20:09 stale[bot]

@alcaeus can we 'un-stale-ify' this ? :)

techbelle avatar Nov 11 '23 03:11 techbelle

@techbelle this is part of the 2.x milestone, so it won't be marked as stale again. That said, I haven't managed to make any progress on this or on the previously mentioned update operators, which IMO should take precedence over this.

alcaeus avatar Nov 13 '23 11:11 alcaeus