Index not created

我与影子孤独终老i 提交于 2019-12-12 04:26:51

问题


I have a document with an index defined.

/** @ODM\Document */
class Stat
{
    /** @ODM\Id(strategy="NONE", type="int") */
    private $id;

    /** @ODM\Field(type="string") */
    private $period;

    /** @ODM\ReferenceOne(targetDocument="Player") */
    private $player;

    /** @ODM\Field(type="string") @ODM\Index */
    private $statType;

However, when I look at the indexes created in the collection, the only index is the _id.

To save the document I'm doing:

$stat = new Documents\Stat();

$stat->setId(1);
$stat->setPlayer($player);
$stat->setPeriod(1);
$stat->setStatType('goal');

$dm->persist($stat);
$dm->flush();

Is there something else I'm not doing?


回答1:


Indexes are not created (nor ensured if they're in sync with mapping) during normal ODM usage.

If you're using Symfony then solving problem is easy, just run doctrine:mongodb:schema:create command from Symfony's console (and if you're using other framework, look for equivalent as command itself is provided by ODM).

If you want to control indexes from your code you can use SchemaManager which provides an API to control "schema" directly (you can also control indexes on per-document basis). Obtaining it is easy: $sm = $dm->getSchemaManager();.




回答2:


// AppBundle/Document

    namespace AppBundle\Document;

    use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
    use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;

    /**
    * @MongoDB\Document(repositoryClass="AppBundle\Repository\ProduitRepository")
    * @MongoDBUnique(fields="$noProduit")
    */
    class Produit
    {
      /**
       * @MongoDB\Id
       */
       protected $id;

      /**
       * @MongoDB\String
       * @MongoDB\UniqueIndex(order="asc")
       */
       protected $noProduit;

       /**
        * @MongoDB\Field(type="string")
        */
       protected $libelle;

      // getter and setter
    }

// AppBundle/Controller

   $dm = $this->get('doctrine_mongodb')->getManager();
   $dm->getSchemaManager()->ensureIndexes();

schema and database will be created automatically when you run your app. For more info visit this link




回答3:


/**
 * @ODM\Document
 * @ODM\Indexes({
 *   @ODM\Index(keys={"statType"="asc"}),
 *   @ODM\UniqueIndex(keys={"period"="asc"})//For example unique index
 * })
 */
class Stat
{
}

Then if you use symfony run php bin/console doctrine:mongodb:schema:create



来源:https://stackoverflow.com/questions/41172585/index-not-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!