kimjingyu 2023. 8. 8. 18:52
728x90

설치하기

  • Homebrew 설치하기 : Homebrew는 다운로드 패키지를 관리할 수 있는 툴로 brew install 프로그램이름을 입력하면 프로그램을 자동으로 다운로드 받아 설치해준다.
  • 터미널 창에 아래 코드를 복사, 붙여넣기 하고 엔터를 입력해주면 된다.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  • mongoDB 설치하기
brew tap mongodb/brew
brew install mongodb-community
  • mongoDB 실행하기
brew services start mongodb-community

Studio 3T

MongoDB를 그래픽으로 볼 수 있게 도와주는 GUI이다.

pymongo로 mongoDB 조작하기

  • pymongo 라이브러리

MongoDB라는 프로그램을 조작하기 위해서는 특별한 라이브러리인 pymongo가 필요하다. 따라서 pip install pymongo 패키지를 설치한다.

사용법

  • 선언
from pymongo import MongoClient

client = MongoClient('localhost', 27017)
  • DB 만들기
db = client.sample  # sample 이라는 이름의  데이터베이스를 만든다.
  • data inserting
db.users.insert_one({'name': 'kim', 'age': 20})
db.users.insert_one({'name': 'lee', 'age': 30})
db.users.insert_one({'name': 'park', 'age': 40})
  • 조회
# 조회

all_users = list(db.users.find({}))
user_age_30 = list(db.users.find({'age': 30}))
print(all_users[0])
print(all_users[0]['name'])
for user in all_users:
    print(user)

user_kim = db.users.find_one({'name': 'kim'})
print(user_kim)
# 특정 키를 제외하고 조회하기
user_lee_except_id = db.users.find_one({'name': 'lee'}, {'_id': False})
print(user_lee_except_id)
  • 수정
# 수정
# db.people.update_many(찾을조건, { '$set': 어떻게바꿀지 })
db.users.update_one({'name': 'kim'}, {'$set': {'age': 19}})
user_kim_updated = db.users.find_one({'name': 'kim'})
print(user_kim_updated)
  •  
728x90