Pymongo 명령어 정리하기

Pymongo 명령어 정리하기

Pymongo
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로 생성할 수 있습니다.

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

collection 생성


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

데이터베이스 확인

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

for item in client.list_databases():
  print(item)
{'name': 'admin', 'sizeOnDisk': 102400, 'empty': False}
{'name': 'config', 'sizeOnDisk': 49152, 'empty': False}
{'name': 'local', 'sizeOnDisk': 73728, 'empty': False}

새롭게 testdb를 생성했지만 db에 데이터가 없는 경우 db가 표시되지 않습니다. testdb가 표시되지 않습니다. DB를 위한 기본 database만 보여지는 것을 확인할 수 있습니다.

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)
{'name': 'admin', 'sizeOnDisk': 102400, 'empty': False}
{'name': 'config', 'sizeOnDisk': 49152, 'empty': False}
{'name': 'local', 'sizeOnDisk': 73728, 'empty': False}

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)
test_collection

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)
{'_id': ObjectId('66ef6e7d7bb27a5ad869d8cb'), 'name': 'tony', 'age': 20}

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

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

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

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

documents = collection.find()
for document in documents:
  print(document)
{'_id': ObjectId('66ef6ea0c5e1f5b844895f73'), 'name': 'mike', 'age': 30}
{'_id': ObjectId('66ef6ea0c5e1f5b844895f74'), 'name': 'mike', 'age': 40}
{'_id': ObjectId('66ef6ea0c5e1f5b844895f75'), 'name': 'bill', 'age': 51}

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

document = collection.find_one({"name":"mike"})
print(document)
{'_id': ObjectId('66ef6ef90ccd16346d93233d'), 'name': 'mike', 'age': 30}

조건으로 document 확인하기

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

documents = collection.find({"age":{"$gte":35}})
for doc in documents:
  print(doc)
{'_id': ObjectId('66ef6f94a596ba8e68f11adc'), 'name': 'mike', 'age': 40}
{'_id': ObjectId('66ef6f94a596ba8e68f11add'), 'name': 'bill', 'age': 51}

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

documents = collection.find({"age":{"$in":[30, 51]}})
for doc in documents:
  print(doc)
{'_id': ObjectId('66ef6ea0c5e1f5b844895f73'), 'name': 'mike', 'age': 30}
{'_id': ObjectId('66ef6ea0c5e1f5b844895f75'), 'name': 'bill', 'age': 51}

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

documents = collection.find({"age":{"$nin":[30, 51]}})
for doc in documents:
  print(doc)
{'_id': ObjectId('66ef6f94a596ba8e68f11adc'), 'name': 'mike', 'age': 40}

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
Date Title Author
Jan 1, 3000 전체 카테고리 gabriel yang
Oct 8, 2024 RESTful API와 PyMongo 통합 방법 gabriel yang
Sep 29, 2024 MongoDB에서의 데이터 모델링 원칙 gabriel yang
Sep 28, 2024 Pymongo 컬렉션 선택 및 생성하기 gabriel yang
Sep 28, 2024 PyMongo 데이터 삽입 gabriel yang
Sep 28, 2024 PyMongo 데이터 수정 gabriel yang
Sep 28, 2024 PyMongo 데이터 삭제 gabriel yang
Sep 27, 2024 Pymongo 데이터베이스 선택 및 생성 gabriel yang
Sep 25, 2024 Pymongo 연결하기 gabriel yang
Sep 22, 2024 MongoDB 구조 (데이터베이스, 컬렉션, 문서) gabriel yang
Sep 22, 2024 Pymongo 데이터베이스 선택 및 생성 gabriel yang
Nov 28, 2023 mongoDB 서비스 시작/종료/상태확인 gabriel yang
Nov 15, 2023 MongoDB 설치 및 명령어 정리하기 gabriel yang
No matching items
Back to BLOG LIST