mongodb - Mongodb Index Creation only if not already exists
问题描述
Is there a command that i can use via javascript in mongo shell that can be used to check if the particular index exists in my mongodb. I am building a script file that would create indexes. I would like that if I run this file multiple number of times then the indexes that already exists are not recreated. I am thinking of using this, will it work:
if(db.collection.getIndexes().find({'name':'index_name'}).count()==0) {
db.collection.createIndex( { abc: 1, def: 1 } , { name: "index_name" } )
}
or, there is any better way to do this ? Also if above code is wrong, please help me with this task.
解决方案
我不确定首先检查是否有好处,除非您打算缓存该响应。
当您调用 时db.collection.createIndex
,它不会重新创建已经存在的索引,它会返回 ok:1
."note" : "all indexes already exist"
db.collection.getIndexes
这将采用与调用或listIndexes
数据库命令相同的数据库锁。首先检查索引是否存在或只是尝试创建它没有太大区别。
推荐阅读
- blogs - 2sxc 博客分页
- angular - 为什么我尝试从本地存储中检索的对象为 null 并且在重新加载后它被定义?
- c# - 是否可以将我的 ML.Net 模型存储在我的 MSSQL 数据库中?
- javascript - 为什么在 sequelize 提供自己的类型时使用 sequelize-typescript?
- python - 如何按(a),(b)拆分文本?
- javascript - 如何在 ArcGIS JS API 3.x 中通过鼠标单击事件选择多个要素
- postgresql - 带有 LIKE 条件的内部连接
- python - VScode 看不到 pyenv python 解释器
- node.js - 返回时打字稿不读取null
- dataframe - 如何在 pyspark 数据框中用 0 替换左连接操作的输出中的空值?