Creating indexes for new collections in MongoDB + PHP

We use MongoDB to collect logs on pageviews.

$collection_name = "logs.".date('Y').".".date('m').".".date('d');
$collection = $this->Mongo->$collection_name;
$collection->insert($pageview);

The code above creates a new collection for each day.

I would like to be able to create an index in the collection above when creating it. Is there any way to do this?

  • In a traditional DBMS, this is done through a schema. Is there something similar in MongoDB? Can I set up a database to create indexes in new collections?
  • If not, what is the way to do this in PHP? I don't want to call securityIndex every time I call insert
+3
source share
2 answers

You can pre-create them, as it’s no secret which collections you will need :)

- :

for ($month = 0; $month < 12; $month++) {
    for ($day = 0; $day < 31, $day++) {
       $c = $db->getCollection("logs.2010.$month.$day");
       $c->ensureIndex(array("foo" => 1));
    }
}

ensureIndex , .

+3

ensureIndex , , ( 1 , ), cron-job , , 11 , / , .

+4

Source: https://habr.com/ru/post/1767930/


All Articles