기본 설치
MongoDB 설치
studio-3t 설치
실행
mongodb://localhost:27017
select
전체 검색
db.emp.find({})
db.getCollection("emp").find({})
단일 조건 검색
db.emp.findOne({e_id:1})
다중 조건 검색
db.emp.find({e_id : {$gt:4}})
db.emp.find({e_id : {$lt:4}})
insert
db.emp.insert({e_id : 2, e_name:'2', gen:'2', addr:'2'})
update
3 3 3 3을 3 6 6 6으로 변환
db.emp.update({e_id:3} ,{'$set': {e_name : '6', gen:'6', addr:'6'}})
delete
e_id가 3인 데이터 삭제
db.emp.deleteOne({e_id : 3})
Python과 연결
라이브러리 설치
pip install pymongo
select
from pymongo import MongoClient
# 방법1 - URI
# mongodb_URI = "mongodb://localhost:27017/"
# client = MongoClient(mongodb_URI)
# 방법2 - HOST, PORT
client = MongoClient(host='localhost', port=27017)
# DB 접근
# db = client.python
db = client['python']
# Collection 접근
# collection = db.emp
col = db['emp']
# 전체 검색
result = col.find()
for i in result :
print(i)
# 단일 검색
result2 = col.find_one({'e_id':1})
print(result2)
# 다중 검색
result3 = col.find({'e_id': {'$lt' : 4}})
for i in result3 :
print(i)
client.close()
insert
from pymongo import MongoClient
client = MongoClient(host='localhost', port=27017)
# DB 접근
# db = client.python
db = client['python']
# Collection 접근
# collection = db.emp
col = db['emp']
data = {
'e_id' : 4,
'e_name' : '4',
'gen' : '4',
'addr' : '4'
}
list = [
{
'e_id' : 5,
'e_name' : '5',
'gen' : '5',
'addr' : '5'
},
{
'e_id' : 6,
'e_name' : '6',
'gen' : '6',
'addr' : '6'
}
]
# x = col.insert_one(data)
x = col.insert_many(list)
print(len(x.inserted_ids))
client.close()
update
from pymongo import MongoClient
client = MongoClient(host='localhost', port=27017)
# DB 접근
# db = client.python
db = client['python']
# Collection 접근
# collection = db.emp
col = db['emp']
x = col.update_one({'e_id':5} ,{'$set': {'e_name' : '6', 'gen':'6', 'addr':'6'}})
print(x.modified_count)
client.close()
delete
from pymongo import MongoClient
client = MongoClient(host='localhost', port=27017)
# DB 접근
db = client['python']
# Collection 접근
col = db['emp']
x = col.delete_one({'e_id':3})
print(x.acknowledged)
client.close()
'Python' 카테고리의 다른 글
[Python] Flask - MVC패턴 (1) | 2024.07.05 |
---|---|
[Python] Flask (0) | 2024.07.03 |
[Python] pymysql 설치 및 실행(select, insert) (0) | 2024.07.02 |
7/1 Homework - 야구게임 pyqt (0) | 2024.07.01 |
서버 배포 (0) | 2024.07.01 |