Pymongo 명령어 정리하기

Pymongo 명령어 정리하기

Database
Pymongo 명령어 정리하기
Author

gabriel yang

Published

November 14, 2023

Pymongo 설치하기

Pymongo를 사용하기위해서 mongo DB를 설치해야합니다. docker를 이용해서 mongo DB를 설치합니다.

# mongo image 다운로드
docker pull mongo

# 다운로드한 docker image 확인
docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
mongo         latest    ee3b4d1239f1   4 weeks ago    748MB
hello-world   latest    9c7a54a9a43c   6 months ago   13.3kB

도커 이미지가 다운로드 완료되면 docker images명령으로 mongo이미지가 다운로드 된 것을 확인할 수 있습니다. VSCODE에서 docker extension을 설치하면 container를 쉽게 실행할 수 있습니다.

# --name : 컨테이너에 이름 부여
# -p : 호스트와 컨테이너 간의 포터의 배포/바인드를 위해 사용
# -e : 컨테이너의 환경변수 설정
# ex) docker run -e FOO=bar python
# -v : 호스트와 컨테이너 간의 볼륨 설정을 위해 사용
# -w : 도커의 작업 디렉토리를 변경
# ex) docker run -w /etc python (컨테이너의 작업 디렉토리를 /etc로 변경)
# -d : 도커를 백그라운드에서 사용하는 경우
docker run -p 27017:27017 --name mongodb -v .:/data/db -d mongo

이제 백그라운드로 실해되고 있는 mongodb container에 접속합니다.

docker exec -it mongodb bash

MongoDB 서버에 연결

DB에 연결할 수 있는 clinet를 생성합니다.

import pymongo
client = pymongo.MongoClient(host="localhost", port=27017)

admin 암호를 설정한 DB에 접속 시 유저명과 암호가 없는 경우 아래와 같은 에러가 발생합니다.

OperationFailure: Command listDatabases requires authentication, full error: {'ok': 0.0, 'errmsg': 'Command listDatabases requires authentication', 'code': 13, 'codeName': 'Unauthorized'}

DB 접근에 필요한 유저명과 이름을 함께 전달합니다.

client = pymongo.MongoClient(host="localhost", username='root', password='1234', port=27017)

collection 삭제

try:
  db = client['test_db']
  collection = db['test_collection']

  collection.drop()
except:
  print("fail")

데이터 베이스 삭제

생성된 데이터 베이스의 삭제는 drop_database를 사용합니다. 테스트을 위해 생성할 test_db가 있다면 데이터베이스를 삭제합니다.

try:
  client.drop_database('test_db')
except e:
  print(e)

데이터 베이스 생성

새로운 데이터베이스는 client의 key로 생성할 수 있습니다. 새롭게 testdb를 생성했지만 db에 데이터가 없는 경우 db가 표시되지 않습니다. testdb가 표시되지 않습니다.

try:
  db = client['test_db']
except:
  print(fail)

for item in client.list_databases():
  print(item)

collection 생성

db = client['test_db']
collection = db['test_collection']

for item in db.list_collections():
  print(item)

데이터베이스 확인

MongoClient를 생성하고 데이터베이스 정보를 list_databases로 확인합니다. 기본적으로 생성된 데이터베이스를 확인할 수 있습니다.

for item in client.list_databases():
  print(item)

collection 및 document 생성

새롭게 생성한 데이터베이스에 collection을 생성하고 document를 추가합니다. document가 추가되면 데이터베이스가 표시됩니다. document가 추가된 후 다시 데이터베이스를 확인하면 데이터베이스가 생성됨을 확인할 수 있습니다.

try:
  db = client['test_db']
  collection = db['test_collection']
except e:
  print(e)
document = {"name": "tony", "age": 20}
result = collection.insert_one(document)

for item in client.list_databases():
  print(item)

document가 추가되었으니 데이터베이스를 다시 확인합니다. 새롭게 생성된 test_db를 확인할 수 있습니다.

collection 확인하기

db에 생성된 collection을 확인하는 방법을 정리합니다. testdb에 생성된 collection 정보를 확인합니다.

try:
  db = client['test_db']
except:
  print("fail")

collection_names = db.list_collection_names()
for name in collection_names:
    print(name)

document 확인하기

PyMongo를 사용하여 MongoDB에서 문서(document)를 확인하는 방법은 find() 메서드를 사용하는 것입니다. 아래는 예시 코드입니다

try:
  db = client['test_db']
  collection = db['test_collection']
  documents = collection.find({})
except:
  print("fail")

for document in documents:
  print(document)

특정 조건을 만족하는 document만 확인하는 방법은 query정보를 딕셔너리 형태로 전달합니다. 검색조건 확인을 위해서 document를 조금 더 추가합니다. 3개의 document가 생성됩니다.

document = {"name": "mike", "age": 30}
collection.insert_one(document)

document = {"name": "mike", "age": 30}
collection.insert_one(document)

document = {"name": "bill", "age": 51}
collection.insert_one(document)

documents = collection.find()
for document in documents:
  print(document)

collection에서 검색하는 document중 하나만 선택 시 find_one을 사용합니다.

document = collection.find_one({"name":"mike"})
print(document)

조건으로 document 확인하기

age 필드에서 나이가 30에 이상이 document를 찾는 경우 $gte를 사용할 수 있습니다.

documents = collection.find({"age":{"$gte":30}})
for doc in documents:
  print(doc)

age 필드의 값이 30 또는 51을 포함한 document를 찾는 경우 $in을 사용합니다.

documents = collection.find({"age":{"$in":[30, 51]}})
for doc in documents:
  print(doc)

age 필드의 값이 30 또는 51을 포함하지 않는 document를 찾는 경우 $nin을 사용합니다.

documents = collection.find({"age":{"$nin":[30, 51]}})
for doc in documents:
  print(doc)

Query Operators는 아래와 같습니다.

Query Operator Col2
$eq x = value (equal) { <field>: { $eq: <value>} }
$gte x >= value (grater than or equal) { <field>: { $gte: <value>} }
$gt x > value (greter than) { <field>: { $gt: <value>} }
$lte x <= value (less then or equal) { <field>: { $lte: <value>} }
$lt x < value (less then) { <field>: { $lt: <value>} }
$in compares each parameter to each document in the collection { field: { $in: [, , … ] } }
$nin select the documents whose field holds an array with no element equal to a value in the specified array. { field: { $nin: [, , … ] } }

References

  1. https://www.tutorialspoint.com/mongodb/index.htm
  2. https://www.tutorialspoint.com/mongodb/index.htm