programing

mongodb에 인덱스가 있는지 확인하는 중

iphone6s 2023. 6. 1. 22:32
반응형

mongodb에 인덱스가 있는지 확인하는 중

mongo shell에서 javascript를 통해 특정 인덱스가 my mongodb에 존재하는지 확인할 수 있는 명령어가 있습니까?인덱스를 만드는 스크립트 파일을 만들고 있습니다.이 파일을 여러 번 실행하면 이미 존재하는 인덱스가 다시 생성되지 않았으면 합니다.

db.collection.getIndexes()를 사용하여 내 DB에 있는 모든 인덱스의 컬렉션을 가져온 다음 이미 존재하는 인덱스를 무시하는 논리를 만들 수 있습니다. 하지만 인덱스를 가져온 다음 인덱스를 만드는 스크립트를 무시하는 명령이 있는지 궁금합니다.다음과 같은 것:

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

MongoDB에서 인덱스를 만드는 것은 동일한 작업입니다.소런닝db.names.createIndex({name:1})인덱스가 아직 존재하지 않는 경우에만 인덱스가 생성합니다.

MongoDB 3.0 기준으로 더 이상 사용되지 않는 별칭입니다.인덱스()가 확실함어떤 것에 대해 조금 더 명확한 색인()createIndex()실제로 그렇습니다.


편집: ZitRo가 요청하는 사항을 댓글로 명확하게 설명해 주셔서 감사합니다.createIndex()이름은 같지만 기존 인덱스와 다른 옵션을 사용하면 오류가 발생합니다.MongoError: Index with name: **indexName** already exists with different options이 질문에서 설명한 바와 같이


확인해야 하는 다른 이유가 있는 경우 다음 두 가지 방법 중 하나로 현재 인덱스 데이터에 액세스할 수 있습니다.

  1. v3.0부터는db.names.getIndexes()어디에names컬렉션의 이름입니다.여기 의사들.
  2. v3.0 이전 버전에서는system.indexes수집 및 작업find아래에 간략하게 설명한 바와 같이.

db.system을 사용합니다.인덱스 및 검색을 수행할 수 있습니다.

예를 들어 'indexname'이라는 인덱스가 있는 경우 다음과 같이 검색할 수 있습니다.

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

특정 컬렉션에서 해당 인덱스를 검색해야 하는 경우 ns 속성을 사용해야 합니다(db 이름을 지정하면 도움이 됩니다).

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

아니면, DB 이름을 포함하는 것이 정말 싫다면...

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

그것을 정리하는 것은...

검사를 완료했습니다.

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

노드 사용JS 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;
  }
}

mongo 드라이버를 사용하여 인덱스가 존재하는지 확인하기 위해 c#에 사용자 지정 메서드를 만들었습니다.

public bool IndexExists<TDocument>(
    IMongoCollection<TDocument> collection, string name)
{
    var indexes = collection.Indexes.List().ToList();
    var indexNames = indexes
        .SelectMany(index => index.Elements)
        .Where(element => element.Name == "name")
        .Select(name => name.Value.ToString());
    
    return indexNames.Contains(name);
}

아마도 우리는 https://docs.mongodb.com/v3.2/reference/method/db.collection.getIndexes/ #db.collection.getIndexes와 같은 것을 사용하여 컬렉션이 어떤 것과 동일한 인덱스를 가지고 있는지 확인할 수 있을 것입니다.

예인 경우 드롭하고 새 항목을 추가하거나 새 항목을 직접 추가합니다.

저의 경우 다음과 같이 했습니다.

   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);
     }

인덱스 이름이 존재하는지 확인하기 위해 작성한 Python 3.5+ pymongo >= 4.1(유형 힌트) 함수입니다(인덱스에 대한 다른 세부사항은 생략됨).

from pymongo import MongoClient
from pymongo.collection import Collection

def check_collection_indexes(db: MongoClient, collection_name: str, index_name: str) -> bool:
    coll: Collection = db[collection_name]
    indexes: dict = coll.index_information()
    
    # assume false
    found = False
    # get length of the index name for substring
    l = len(index_name)
    for k in indexes.keys():
        # Substring the keys and check for match
        if k[:l] == index_name:
            found = True
            break
        else:
            found = False
    return found

인덱스가 존재하면 True를 반환하고, 그렇지 않으면 False 출력을 사용하여 인덱스를 생성/재작성하는 다른 함수를 호출할 수 있습니다.

언급URL : https://stackoverflow.com/questions/35019313/checking-if-an-index-exists-in-mongodb

반응형