mongodb 检查mongodb中是否存在索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35019313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:37:32  来源:igfitidea点击:

Checking if an Index exists in mongodb

mongodb

提问by CSC

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.

是否有我可以通过 mongo shell 中的 javascript 使用的命令,该命令可用于检查特定索引是否存在于我的 mongodb 中。我正在构建一个可以创建索引的脚本文件。我希望如果我多次运行此文件,则不会重新创建已存在的索引。

I can use db.collection.getIndexes() to get the collection of all the indexes in my db and then build a logic to ignore the ones that already exists but i was wondering if there is command to get an index and then ignore a script that creates the index. Something like:

我可以使用 db.collection.getIndexes() 来获取我的数据库中所有索引的集合,然后构建一个逻辑来忽略已经存在的那些,但我想知道是否有命令来获取索引然后忽略脚本创建索引。就像是:

If !exists(db.collection.exists("indexname")) 
{
    create  db.collectionName.CreateIndex("IndexName")
}

回答by metame

Creating indexes in MongoDB is an idempotent operation. So running db.names.createIndex({name:1})would create the index only if it didn't already exist.

在 MongoDB 中创建索引是一个幂等操作。因此db.names.createIndex({name:1}),仅当索引不存在时,运行才会创建索引。

The deprecated (as of MongoDB 3.0) alias for createIndex()is ensureIndex()which is a bit clearer on what createIndex()actually does.

createIndex()的已弃用(从 MongoDB 3.0 开始)别名是ensureIndex(),它对createIndex()实际作用更清楚一些。



Edit:Thanks to ZitRo for clarifying in comments that calling createIndex()with the same name but different options than an existing index will throw an error MongoError: Index with name: **indexName** already exists with different optionsas explained in this question.

编辑:感谢 ZitRo 在评论中澄清createIndex()使用与现有索引相同的名称但不同的选项调用将引发错误,MongoError: Index with name: **indexName** already exists with different options本问题所述



If you have other reasons for checking, then you can access current index data one of two ways:

如果您有其他原因需要检查,那么您可以通过以下两种方式之一访问当前索引数据:

  1. As of v3.0, we can use db.names.getIndexes()where namesis the name of the collection. Docs here.
  2. Before v3.0, you can access the system.indexescollection and do a findas bri describes below.
  1. 从 v3.0 开始,我们可以使用db.names.getIndexes()wherenames是集合的名称。文档在这里
  2. 在 v3.0 之前,您可以访问该system.indexes集合并find按照 bri描述执行以下操作

回答by bri

Use db.system.indexesand search on it.

使用db.system.indexes并对其进行搜索。

If, for example, you have an index called 'indexname', you can search for it like this:

例如,如果您有一个名为“indexname”的索引,您可以像这样搜索它:

db.system.indexes.find({'name':'indexname'});

If you need to search for that index on a specific collection,then you need to use the ns property (and, it would be helpful to have the db name).

如果您需要在特定集合上搜索该索引,则需要使用 ns 属性(并且,拥有 db 名称会很有帮助)。

db.system.indexes.find({'name':'indexname', 'ns':'dbname.collection'});

Or, if you absolutely hate including the db name...

或者,如果您绝对讨厌包含数据库名称...

db.system.indexes.find({'name':'indexname', 'ns': {$regex:'.collection$'}});

Pulling that together...

拉在一起...

So, you're finished check would be:

所以,你完成的检查将是:

if(db.system.indexes.find({name:'indexname',ns:{$regex:'.collection$'}}).count()==0) { 
    db.collection.createIndex({blah:1},{name:'indexname'}) 
}

回答by ctf0

maybe we can use something like https://docs.mongodb.com/v3.2/reference/method/db.collection.getIndexes/#db.collection.getIndexesto check if the collection have an index equal to something ?

也许我们可以使用https://docs.mongodb.com/v3.2/reference/method/db.collection.getIndexes/#db.collection.getIndexes 之类的东西来检查集合是否具有等于某物的索引?

if yes then drop and add the new one or add the new one directly

如果是,则删除并添加新的或直接添加新的

回答by Ramesh Papaganti

In my case i did as follows.

在我的情况下,我做了如下。

   DBCollection yourcollectionName = mt.getCollection("your_collection");
    if (yourcollectionName.getIndexInfo() == null || yourcollectionName.getIndexInfo().isEmpty()) {         
      DBObject indexOptions = new BasicDBObject();
      indexOptions.put("pro1", 1);
      indexOptions.put("pro2", 1);       
      yourcollectionName.createIndex(indexOptions, "name_of_your_index", true);
     }

回答by Dvir Arad

Using nodeJS MongoDB driver version 2.2:

使用 nodeJS MongoDB 驱动程序 2.2 版:


const MongoClient = require('mongodb').MongoClient;

exports.dropOldIndexIfExist = dropOldIndexIfExist;
async function dropOldIndexIfExist() {
  try {
    const mongoConnection = MongoClient.connect('mongodb://localhost:27017/test');
    const indexName = 'name_1';
    const isIndexExist = await mongoConnection.indexExists(indexName);
    if (isIndexExist === true) {
      await mongoConnection.dropIndex(indexName);
    }
  } catch (err) {
    console.error('dropOldIndexIfExist', err.message);
    throw err;
  }
}