다음을 통해 공유


Python을 사용하여 MongoDB 데이터베이스 관리

적용 대상: MongoDB

Azure Cosmos DB의 MongoDB 서버는 다음과 같은 MongoDB에 대한 일반적인 Python 패키지에서 사용할 수 있습니다.

  • 동기 Python 애플리케이션용 PyMongo, 이 문서에서 사용됩니다.
  • 비동기 Python 애플리케이션용 Motor

참고 항목

예제 코드 조각은 GitHub에서 Python 프로젝트로 사용할 수 있습니다.

데이터베이스 이름 지정

Azure Cosmos DB에서 데이터베이스는 네임스페이스와 유사합니다. 데이터베이스를 만들 때 데이터베이스 이름은 데이터베이스 리소스 및 모든 자식 리소스에 액세스하는 데 사용되는 URI 세그먼트를 형성합니다.

다음은 데이터베이스 이름을 지정할 때의 몇 가지 빠른 규칙입니다.

  • 데이터베이스 이름을 3~63자 길이로 유지
  • 데이터베이스 이름에는 소문자, 숫자 또는 대시(-) 문자만 포함될 수 있습니다.
  • 데이터베이스 이름은 소문자나 숫자로 시작해야 합니다.

만들어지면 데이터베이스에 대한 URI는 다음과 같은 형식입니다.

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>

데이터베이스 인스턴스 가져오기

데이터베이스는 컬렉션 및 해당 문서를 보유합니다. 데이터베이스에 액세스하려면 MongoClient의 특성 스타일 액세스 또는 사전 스타일 액세스를 사용합니다. 자세한 내용은 데이터베이스 가져오기를 참조하세요.

다음 코드 조각에서는 클라이언트 연결을 이미 만들었으며 이러한 코드 조각 뒤에 클라이언트 연결을 닫은 것으로 가정합니다.

서버 정보 가져오기

MongoClient 클래스의 server_info 메서드를 사용하여 서버 정보에 액세스합니다. 이 정보를 얻으려면 데이터베이스 이름을 지정할 필요가 없습니다. 반환되는 정보는 MongoDB에만 해당되며 Azure Cosmos DB 플랫폼 자체를 나타내지 않습니다.

MongoClient.list_database_names 메서드를 사용하여 데이터베이스를 나열하고 MongoClient.db.command 메서드를 사용하여 데이터베이스에 MongoDB 명령을 실행할 수도 있습니다.

# Get server information
for k, v in client.server_info().items():
    print("Key: {} , Value: {}".format(k, v))

# Get server status of admin database
print("Server status {}".format(client.admin.command("serverStatus")))

# List databases
databases = client.list_database_names()
print("Databases: {}".format(databases))

위의 코드 조각은 다음 예제 콘솔 출력과 비슷한 출력을 표시합니다.

Key: version , Value: 3.6.0
Key: versionArray , Value: [3, 6, 0, 0]
Key: bits , Value: 64
Key: maxBsonObjectSize , Value: 16777216
Key: ok , Value: 1.0
Server status {'ok': 1.0}
Databases: ['adventureworks']

데이터베이스가 있나요?

Python용 PyMongo 드라이버는 데이터베이스에 액세스할 때 데이터베이스가 없는 경우 데이터베이스를 만듭니다. 그러나 대신 MongoDB 확장 명령을 사용하여 Azure Cosmos DB의 API for MongoDB에 저장된 데이터를 관리하는 것이 좋습니다. 데이터베이스가 없는 경우 새 데이터베이스를 만들려면 다음 코드 조각과 같이 데이터베이스 확장 만들기를 사용합니다.

데이터베이스를 사용하기 전에 데이터베이스가 이미 있는지 확인하려면 list_database_names 메서드를 사용하여 현재 데이터베이스 목록을 가져옵니다.

# Get list of databases
databases = client.list_database_names()
if not databases:
    print("No databases found")

# Does database exist?
DB_NAME = "adventureworks"
if DB_NAME in databases:
    print("Database exists: {}".format(DB_NAME))
else:
    client[DB_NAME].command(
        {"customAction": "CreateDatabase", "offerThroughput": 400}
    )
    print("Created db '{}' with shared throughput.\n".format(DB_NAME))

위의 코드 조각은 다음 예제 콘솔 출력과 비슷한 출력을 표시합니다.

Database exists: adventureworks

데이터베이스, 컬렉션 및 문서 수 목록 가져오기

프로그래밍 방식으로 MongoDB 서버를 관리하는 경우 서버에 있는 데이터베이스 및 컬렉션과 각 컬렉션의 문서 수를 아는 것이 좋습니다. 자세한 내용은 다음을 참조하세요.

# Get list of databases
databases = client.list_database_names()

# Loop through databases
for db in databases:
    print("Database: {}".format(db))

    # Get list of collections
    collections = client[db].list_collection_names()

    # Loop through collections
    for col in collections:
        print("\tCollection: {}".format(col))

        # Get document count
        doc_count = client[db][col].count_documents({})
        print("\tDocument count: {}".format(doc_count))

위의 코드 조각은 다음 예제 콘솔 출력과 비슷한 출력을 표시합니다.

Database: adventureworks
        Collection: products_new
        Document count: 1
        Collection: products
        Document count: 3
Database: testdb
        Collection: mycoll
        Document count: 1

데이터베이스 개체 인스턴스 가져오기

데이터베이스가 없으면 데이터베이스에 액세스할 때 Python용 PyMongo 드라이버에서 데이터베이스를 만듭니다. 그러나 대신 MongoDB 확장 명령을 사용하여 Azure Cosmos DB의 API for MongoDB에 저장된 데이터를 관리하는 것이 좋습니다. 이 패턴은 위의 데이터베이스가 있나요? 섹션에 나와 있습니다.

PyMongo로 작업할 때 MongoClient 인스턴스에서 특성 스타일 액세스를 사용하여 데이터베이스에 액세스합니다. 데이터베이스 인스턴스가 있으면 아래와 같이 데이터베이스 수준 작업을 사용할 수 있습니다.

collections = client[db].list_collection_names()

PyMongo 드라이버를 사용한 데이터베이스 작업에 대한 개요는 데이터베이스 수준 작업을 참조하세요.

데이터베이스 삭제

데이터베이스는 MongoClient의 drop_database 메서드를 사용하여 서버에서 제거됩니다.

DB_NAME = input("Enter database name to drop: ")
if DB_NAME in client.list_database_names():
    print("Dropping database: {}".format(DB_NAME))
    client.drop_database(DB_NAME)
else:
    print("Didn't find database: {}".format(DB_NAME))

위의 코드 조각은 다음 예제 콘솔 출력과 비슷한 출력을 표시합니다.

Enter database name to drop: adventureworks
Dropping database: adventureworks

참고 항목