일상 코딩
몽고DB / MongoDB CRUD 명령어 실습 예제 본문
728x90
2.1 연결하기¶
In [ ]:
import pymongo
In [ ]:
host_info2 = 'mongodb://ubuntu:1234@127.0.0.1:27017'
conn = pymongo.MongoClient(host_info2)
print(conn)
MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True)
2.2 mydbs Database 사용하기¶
In [ ]:
# 몽고db 객체 생성
knowledge = conn.mydbs
In [ ]:
# 이렇게도 가능하다.
knowledge = conn["mydbs"]
In [ ]:
print(dir(knowledge))
['_BaseObject__codec_options', '_BaseObject__read_concern', '_BaseObject__read_preference', '_BaseObject__write_concern', '_Database__client', '_Database__incoming_copying_manipulators', '_Database__incoming_manipulators', '_Database__name', '_Database__outgoing_copying_manipulators', '_Database__outgoing_manipulators', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_apply_incoming_copying_manipulators', '_apply_incoming_manipulators', '_command', '_create_or_update_user', '_current_op', '_default_role', '_fix_incoming', '_fix_outgoing', '_list_collections', '_read_preference_for', '_retryable_read_command', '_write_concern_for', 'add_son_manipulator', 'add_user', 'aggregate', 'authenticate', 'client', 'codec_options', 'collection_names', 'command', 'create_collection', 'current_op', 'dereference', 'drop_collection', 'error', 'eval', 'get_collection', 'incoming_copying_manipulators', 'incoming_manipulators', 'last_status', 'list_collection_names', 'list_collections', 'logout', 'name', 'next', 'outgoing_copying_manipulators', 'outgoing_manipulators', 'previous_error', 'profiling_info', 'profiling_level', 'read_concern', 'read_preference', 'remove_user', 'reset_error_history', 'set_profiling_level', 'system_js', 'validate_collection', 'watch', 'with_options', 'write_concern']
In [ ]:
print(knowledge.name)
mydbs
2.3 it_collection이라는 collection 사용하기 (없으면 만들어 진다.)¶
In [ ]:
# collection 객체 생성
# 방법 1: 명시적(explicit) create_collection, 존재할 경우 에러 출력
# knowledge_it = knowledge.create_collection("knowledge_it")
# 방법 2: collection이 있으면 연결하고, 없으면 생성, 서버 적용은 document insert 시점에 생성
knowledge_it = knowledge.knowledge_it
In [ ]:
knowledge_it
Out[ ]:
Collection(Database(MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True), 'mydbs'), 'knowledge_it')
In [ ]:
knowledge_it.name
Out[ ]:
'knowledge_it'
2.4 Document INSERT 하기¶
- ## insert_one()
## insert_many()
### insert_one()
- ### mongodb shell 명령어: insertOne()
In [ ]:
post = {
"author":"Mike",
"text":"My first blog post!",
"tags":["mongodb","python","pymongo"]
}
post
Out[ ]:
{'author': 'Mike', 'text': 'My first blog post!', 'tags': ['mongodb', 'python', 'pymongo']}
In [ ]:
knowledge_it.insert_one(post)
Out[ ]:
<pymongo.results.InsertOneResult at 0x7f813296bf80>
In [ ]:
knowledge_it.insert_one({
"author":"joy Lee",
"age":45
})
Out[ ]:
<pymongo.results.InsertOneResult at 0x7f8132991a00>
- ## insert_many()
In [ ]:
knowledge_it.insert_many(
[
{"author":"joy Ahn","age":25},
{"author":"joy", "age":35}
]
)
Out[ ]:
<pymongo.results.InsertManyResult at 0x7f8132994fc0>
- ## Document INSERT 하면, _id(primary key)를 확인하는 방법
In [ ]:
post = {
"author":"joy",
"text":"My first blog post!"
}
post
Out[ ]:
{'author': 'joy', 'text': 'My first blog post!'}
In [ ]:
post_id = knowledge_it.insert_one(post)
post_id
Out[ ]:
<pymongo.results.InsertOneResult at 0x7f8131113a00>
- # _id 확인
- ## primary key
In [ ]:
post_id.inserted_id
Out[ ]:
ObjectId('61822f1acedc92ea0c9bddd4')
- ## estimated_document_count() 메서드는 컬렉션 객체와 함께 쓰여서 총 Document 수를 알려줌
- ## count_documents({}) -권장 함수
- ### count() 함수는 최신 pymongo 라이브러리에서는 권장되지 않음.
- ## count_documents({}) -권장 함수
In [ ]:
knowledge_it.count_documents({})
Out[ ]:
5
- ## list와 dictionary를 활용하여 insert 하기
In [ ]:
# 리스트, 객체 삽입 가능
knowledge_it.insert_one({
'title':'암살',
'castings':['이정재','전지현','하정우']
})
knowledge_it.insert_one(
{
'title':'실미도',
'castings':['설경구','안성기'],
'datetime': {
'year':'2003',
'month':3,
'val':{'a':{'b':1}}
}
}
)
Out[ ]:
<pymongo.results.InsertOneResult at 0x7f81310fd880>
In [ ]:
data = list()
data.append({'name':'aaron','age':20})
data.append({'name':'bob','age':30})
data.append({'name':'cathy','age':25})
data.append({'name':'dvaid','age':27})
data.append({'name':'erick','age':28})
data.append({'name':'fox','age':32})
data.append({'name':'hmm'})
print(knowledge_it.insert_many(data))
data
<pymongo.results.InsertManyResult object at 0x7f8131125b80>
Out[ ]:
[{'name': 'aaron', 'age': 20, '_id': ObjectId('61823608cedc92ea0c9bddd7')}, {'name': 'bob', 'age': 30, '_id': ObjectId('61823608cedc92ea0c9bddd8')}, {'name': 'cathy', 'age': 25, '_id': ObjectId('61823608cedc92ea0c9bddd9')}, {'name': 'dvaid', 'age': 27, '_id': ObjectId('61823608cedc92ea0c9bddda')}, {'name': 'erick', 'age': 28, '_id': ObjectId('61823608cedc92ea0c9bdddb')}, {'name': 'fox', 'age': 32, '_id': ObjectId('61823608cedc92ea0c9bdddc')}, {'name': 'hmm', '_id': ObjectId('61823608cedc92ea0c9bdddd')}]
In [ ]:
knowledge_it.estimated_document_count()
Out[ ]:
14
2.5 Document 검색 하기(읽기) ( find_one()과 find() )¶
- ## find_one() 메서드 : 가장 빨리 검색되는 하나 검색하기
In [ ]:
knowledge_it.find_one()
Out[ ]:
{'_id': ObjectId('6182272ecedc92ea0c9bddd0'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': ['mongodb', 'python', 'pymongo']}
In [ ]:
joy = knowledge_it.find_one({"author":"joy"})
joy
Out[ ]:
{'_id': ObjectId('61822e54cedc92ea0c9bddd3'), 'author': 'joy', 'age': 35}
- # find_one()
- ## 안에 조건을 넣을 때는 사전 형식으로 해야한다.
- # { key : value }
- # find() 메서드 : 검색되는 모든 Document 읽어오기
In [ ]:
docs = knowledge_it.find()
In [ ]:
for doc in docs:
print(doc)
{'_id': ObjectId('6182272ecedc92ea0c9bddd0'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': ['mongodb', 'python', 'pymongo']} {'_id': ObjectId('61822dcccedc92ea0c9bddd1'), 'author': 'joy Lee', 'age': 45} {'_id': ObjectId('61822e54cedc92ea0c9bddd2'), 'author': 'joy Ahn', 'age': 25} {'_id': ObjectId('61822e54cedc92ea0c9bddd3'), 'author': 'joy', 'age': 35} {'_id': ObjectId('61822f1acedc92ea0c9bddd4'), 'author': 'joy', 'text': 'My first blog post!'} {'_id': ObjectId('6182352ccedc92ea0c9bddd5'), 'title': '암살', 'castings': ['이정재', '전지현', '하정우']} {'_id': ObjectId('6182352ccedc92ea0c9bddd6'), 'title': '실미도', 'castings': ['설경구', '안성기'], 'datetime': {'year': '2003', 'month': 3, 'val': {'a': {'b': 1}}}} {'_id': ObjectId('61823608cedc92ea0c9bddd7'), 'name': 'aaron', 'age': 20} {'_id': ObjectId('61823608cedc92ea0c9bddd8'), 'name': 'bob', 'age': 30} {'_id': ObjectId('61823608cedc92ea0c9bddd9'), 'name': 'cathy', 'age': 25} {'_id': ObjectId('61823608cedc92ea0c9bddda'), 'name': 'dvaid', 'age': 27} {'_id': ObjectId('61823608cedc92ea0c9bdddb'), 'name': 'erick', 'age': 28} {'_id': ObjectId('61823608cedc92ea0c9bdddc'), 'name': 'fox', 'age': 32} {'_id': ObjectId('61823608cedc92ea0c9bdddd'), 'name': 'hmm'}
In [ ]:
docs = knowledge_it.find({"author":"joy"})
- ## sort()와 함께 쓰기
In [ ]:
for post in knowledge_it.find().sort("age"):
print(post)
{'_id': ObjectId('6182272ecedc92ea0c9bddd0'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': ['mongodb', 'python', 'pymongo']} {'_id': ObjectId('61822f1acedc92ea0c9bddd4'), 'author': 'joy', 'text': 'My first blog post!'} {'_id': ObjectId('6182352ccedc92ea0c9bddd5'), 'title': '암살', 'castings': ['이정재', '전지현', '하정우']} {'_id': ObjectId('6182352ccedc92ea0c9bddd6'), 'title': '실미도', 'castings': ['설경구', '안성기'], 'datetime': {'year': '2003', 'month': 3, 'val': {'a': {'b': 1}}}} {'_id': ObjectId('61823608cedc92ea0c9bdddd'), 'name': 'hmm'} {'_id': ObjectId('61823608cedc92ea0c9bddd7'), 'name': 'aaron', 'age': 20} {'_id': ObjectId('61822e54cedc92ea0c9bddd2'), 'author': 'joy Ahn', 'age': 25} {'_id': ObjectId('61823608cedc92ea0c9bddd9'), 'name': 'cathy', 'age': 25} {'_id': ObjectId('61823608cedc92ea0c9bddda'), 'name': 'dvaid', 'age': 27} {'_id': ObjectId('61823608cedc92ea0c9bdddb'), 'name': 'erick', 'age': 28} {'_id': ObjectId('61823608cedc92ea0c9bddd8'), 'name': 'bob', 'age': 30} {'_id': ObjectId('61823608cedc92ea0c9bdddc'), 'name': 'fox', 'age': 32} {'_id': ObjectId('61822e54cedc92ea0c9bddd3'), 'author': 'joy', 'age': 35} {'_id': ObjectId('61822dcccedc92ea0c9bddd1'), 'author': 'joy Lee', 'age': 45}
- # 2.6 Document Update하기
- ## update_one()
- ## update_many()
- ## update_one() : 가장 먼저 검색되는 한 Document만 수정하기
In [ ]:
knowledge_it.find_one({"author":"joy"})
Out[ ]:
{'_id': ObjectId('61822e54cedc92ea0c9bddd3'), 'author': 'joy', 'age': 35}
In [ ]:
knowledge_it.update_one(
{"author":"joy"},
{"$set" : {"text":"Hi Joy"}}
)
Out[ ]:
<pymongo.results.UpdateResult at 0x7f8131124180>
In [ ]:
docs = knowledge_it.find({"author":"joy Lee"})
In [ ]:
for doc in docs:
print(doc)
{'_id': ObjectId('61822dcccedc92ea0c9bddd1'), 'author': 'joy Lee', 'age': 45}
- ## update_many() : 조건에 맞는 모든 Document 수정하기
In [ ]:
knowledge_it.update_many(
{"author":"joy Lee"},
{"$set":{"age":30}}
)
Out[ ]:
<pymongo.results.UpdateResult at 0x7f8131092f80>
- # Document 삭제하기
- ## delete_one()
- ## delete_many()
- ## delete_one() 메서드 : 가장 먼저 검색되는 한 Document만 삭제하기
In [ ]:
docs = knowledge_it.find({"author":"joy Lee"})
In [ ]:
for doc in docs:
print(doc)
{'_id': ObjectId('61822dcccedc92ea0c9bddd1'), 'author': 'joy Lee', 'age': 30}
In [ ]:
knowledge_it.delete_one({"author":"joy Lee"})
Out[ ]:
<pymongo.results.DeleteResult at 0x7f8131096040>
In [ ]:
docs = knowledge_it.find({"author":"joy Lee"})
for doc in docs:
print(doc)
- ## delete_many() 메서드 : 조건에 맞는 모든 Document 삭제하기
In [ ]:
knowledge_it.delete_many({"author":"joy Lee"})
Out[ ]:
<pymongo.results.DeleteResult at 0x7f8132aa2540>
In [ ]:
knowledge_it.count_documents({"author":"joy Lee"})
Out[ ]:
0
In [ ]:
import pymongo
conn = pymongo.MongoClient(host_info2)
books = conn.books
# it_book = books.create_collection("it_book")
it_book = books.it_book
In [ ]:
data = list()
for idx in range(100):
data.append(
{
"author":"Joy Lee",
"publisher":"fun-coding.org",
"number":idx
}
)
In [ ]:
# CRUD - Create(Insert)
it_book.insert_many(data)
Out[ ]:
<pymongo.results.InsertManyResult at 0x7f813299d2c0>
In [ ]:
# CRUD - Update
it_book.update_many(
{},
{"$set":{"publisher":"www.fun-coding.org"}}
)
Out[ ]:
<pymongo.results.UpdateResult at 0x7f811b594f80>
In [ ]:
# CRUD - Delete
it_book.delete_many({})
728x90
'DataBase > MongoDB' 카테고리의 다른 글
[링크] 리눅스 Ubuntu 몽고DB 설치 가이드 (0) | 2021.11.05 |
---|---|
몽고 DB CRUD 및 사용 메뉴얼(공식 문서) (0) | 2021.11.03 |