在 MongoDB 中的新集合上创建索引 + PHP
我们使用 MongoDB 收集浏览量日志。
$collection_name = "logs.".date('Y').".".date('m').".".date('d');
$collection = $this->Mongo->$collection_name;
$collection->insert($pageview);
上面的代码每天都会创建一个新的集合。
我希望能够在创建上述集合时为其创建索引。有办法做到这一点吗?
- 在传统的 RDBMS 中,这是通过模式来完成的。 MongoDB中有类似的东西吗?是否可以配置数据库以在新集合上创建索引?
- 如果没有,在 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?
- 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?
- If not, what is the best way to accomplish this in PHP? I don't want to call ensureIndex everytime I call insert
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了避免在每次插入时调用
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.您可以预先创建它们,因为您需要什么集合并不完全是秘密:)
您可以运行如下命令:
ensureIndex
将创建集合(如果它尚不存在)。You can pre-create them, since it's not exactly a secret what collections you'll need :)
You could run something like:
ensureIndex
will create the collection if it doesn't already exist.