在 MongoDB 中的新集合上创建索引 + PHP

发布于 2024-09-26 05:14:40 字数 441 浏览 5 评论 0原文

我们使用 MongoDB 收集浏览量日志。

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

上面的代码每天都会创建一个新的集合。

我希望能够在创建上述集合时为其创建索引。有办法做到这一点吗?

  1. 在传统的 RDBMS 中,这是通过模式来完成的。 MongoDB中有类似的东西吗?是否可以配置数据库以在新集合上创建索引?
  2. 如果没有,在 PHP 中实现此目的的最佳方法是什么?我不想每次调用 insert 时都调用 ensureIndex

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 every day.

I would like to be able to create an index on the above collection when it is created. Is there anyway to do this?

  1. In a traditional RDBMS, this is accomplished through the schema. Is there anything similar in MongoDB? Is it possible to configure the database to create indexes on new collections?
  2. If not, what is the best way to accomplish this in PHP? I don't want to call ensureIndex everytime I call insert

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多情癖 2024-10-03 05:14:40

为了避免在每次插入时调用 ensureIndex ,我认为最好的选择(除了仅使用 1 个存在性能问题的集合之外)是每天在晚上 11 点运行一个 cron 作业,这会创建对应于即将到来的一天的集合的集合/索引。

To avoid calling ensureIndex on every insert I think your best bet (besides using only 1 collection which you have performance issues with) would be to run a cron-job every day at, say, 11pm which creates the collection/index for the collection corresponding to the upcoming day.

财迷小姐 2024-10-03 05:14:40

您可以预先创建它们,因为您需要什么集合并不完全是秘密:)

您可以运行如下命令:

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 将创建集合(如果它尚不存在)。

You can pre-create them, since it's not exactly a secret what collections you'll need :)

You could run something like:

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 will create the collection if it doesn't already exist.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文