How do I use my own data as the ID for a Doctrine MongoDB mapped document instead of the automatically generated Object ID?

doctrine, mongodb, symfony

Solution

<?php

namespace Acme\HelloWorld\Model;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class KindWord {

  /**
   * @MongoDB\Id(strategy="NONE")
   * @var string
   */
  private $word;

  public function getWord() {
    return $this->word;
  }

  public function setWord($word) {
    $this->word = $word;
  }

}

Just make sure you set `$word` before calling `persist()`.

Problem

The MongoDB documentation on Object IDs recommends using custom keys in a certain case: If your document has a natural primary key that is immutable we recommend you use that in _id instead of the automatically generated ids. How can I define a simple model object that does exactly this?

Original source