本文介绍了Mongodb:何时调用ensureIndex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该打电话给ensureIndex?在插入单个记录之前,插入单个记录之前,或者在调用find()之前?

When should I call ensureIndex? Before inserting a single record, after inserting a single record, or before calling find()?

问候,

Johnny

推荐答案

看来我的评论有点被误解了,所以我会澄清一下。只要在第一次调用find()之前在某个时刻调用,它就没那么重要了。换句话说,创建时它并不重要索引,只要它在你预期使用它之前就已存在。

It seems my comment has been a little misunderstood, so I'll clarify. It doesn't really matter when you call it so long as it's called at some point before you call find() for the first time. In other words, it doesn't really matter when you create the index, as long as it's there before you expect to use it.

我见过的一个常见模式是同时编码 ensureIndex (以及与 find()调用相同的地方)。 ensureIndex 将检查索引是否存在,如果不存在则创建索引。在调用find()之前调用ensureindex毫无疑问会有一些开销(尽管很小),所以最好不要这样做。

A common pattern that I've seen a lot is coding the ensureIndex at the same time (and in the same place) as the find() call. ensureIndex will check if the index exists and create it if it doesn't. There is undoubted some overhead (albeit very small) in calling ensureindex before ever call to find() so it's preferable not to do this.

我在代码中调用 ensureIndex 来简化部署并避免单独管理数据库和代码库。易于部署的权衡平衡了后续调用ensureIndex(对我而言)的冗余。

I do call ensureIndex in code to simplify deployments and to avoid having to manage the db and codebase separately. The tradeoff of ease of deployment balances out the redundancy of subsequent calls to ensureIndex (for me.)

这篇关于Mongodb:何时调用ensureIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 06:01