1

How to store a document inside another document, with Doctrine ODM?

I don't see an Array or Json type in the documentation.

I would like to be able to do something like this:

class Post {

    /**
     * @MongoDB\String
     */
    protected $body;

    /**
     * @MongoDB\Array
     */
    protected $comments = array();

}

I don't want to have a separate collection for comments. I want them saved inside each post.

HappyDeveloper
  • 12,480
  • 22
  • 82
  • 117

3 Answers3

2
/**
 * @MongoDB\Document
 */
class Post
{
    /**
     * @MongoDB\Id
     */
    private $id;

    /**
     * @MongoDB\String
     */
    private $body;

    /**
     * @MongoDB\EmbedMany(targetDocument="Comment")
     */
    private $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }
}

/**
 * @MongoDB\EmbeddedDocument
 */
class Comment
{
    /**
     * @MongoDB\String
     */
    private $body;
}

But note that comments are not good candidates for embedding — contrary to probably the most popular example of embeds in MongoDB. I started with comments as embeds too, but then run into some problems and decided to store them in a separate collection. I don't remember all the problems, but the main one was the inability to sort comments on the database side. The quick solution was to sort them on the client side, but when it comes to pagination, it just doesn't scale.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
0

I think this is what you're looking for: http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/embedded-mapping.html

GGGforce
  • 634
  • 1
  • 8
  • 19
-2

In my __construct() I need

new \Doctrine\Common\Collections\ArrayCollection();

where you just have

new ArrayCollection();
Adam Knowles
  • 492
  • 5
  • 14