study/PYTHON

pymongo 함수 정리

김팥빵_ 2024. 9. 30. 21:58

1. client, DB, collection 생성

  • Collection : mongoDB에 저장되어 있는 document들을 관리하고 있는 그룹(=table)
from pymongo import MongoClient
  • client 함수
    • client = MongoClient(uri) *uri는 mongoDB의 최초 받아오는 주소
  • db 함수 
    • db = client.['database이름'] ex. db = client['fruitStore']
    • db = client.database이름 ex. db = client.fruitStore
  • Collection list 확인
    • print(db.list_collection_names())

2. Document insert(삽입)

  • Document : "json 형식"의 mongoDB에서 사용되는 data(관계형 DB에서의 table의 row 역할)
  • Document data 샘플(json 형식의 data)
import datetime
post = {
	"author" : "ktx",
    "text" : "mongoDB test",
    "tags" : [["mongodb": "1"], 
    		["oracle": "2"],
            ["python": "3"],
            ["java spring": "4"]]
    "date" : datetime.datetime.utcnow()
}

post2 = {
	"author" : "ktx2",
    "text" : "mongoDB test",
    "tags" : [["ruby": "5"], 
    		["mysql": "6"],
            ["flask": "7"],
            ["java": "8"]]
    "date" : datetime.datetime.utcnow()
}

 

  • insert_one
    • document가 db에 insert되면 "_id"라는 unique key가 자동으로 생성된다.
    • insert_one() 함수는 반환값으로 InsertOneResult를 반환 (ObjectId 생성)
post_id = collection.insert_one(post).inserted_id

 

  • insert_many (bulk)
    • 여러개의 document를 한번에 insert 한다.
    • insert될 json 형식의 data들은 list안에 있어야 한다.
new_posts = []
'''
	new_posts list안에 insert될 json 형식의 data들을 append
'''
result = collection.insert_many(new_posts)

 

3. Document Find(찾기)

  • find_one
    • 단일 document를 검색한다.
    • query문을 추가해 검색할 때 필터 적용처럼 사용 가능하다.(ex. find_one({"author":"ktx"}))
    • ObjectId를 query문으로 사용할 수 있다. (ex. find_one({"_id":post_id}))
    • ObjectId는 String 값이 아니므로 String으로 쓰려면 str()을 사용해 변환함. (bson.objectid의 ObjectId사용) ***BSON : 바이너리로 인코딩 된 json과 유사한 문서
import pprint

pprint.pprint(collection.find_one())
pprint.pprint(collection.find_one({"author":"ktx"}))

print(post_id)
pprint.pprint(collection.find_one({"_id":post_id}))

print('change objectId to string')
pprint.pprint(collection.find_one({"_id":str(post_id)}))

from bson.objectid import ObjectId
print('change string to objectId')
pprint.pprint(collection.find_one({"_id":ObjectId(str(post_id))}))

 

  • find
    • 다중 document 검색
    • 반환 값으로 Cursor imstance 반환***Cursor : query문을 만족하는 document들을 담고 있는 instance(iterated)
    • query문을 사용해 조건에 만족하는 document들만 볼 수 있다.
# 모든 document들을 반환
for document in collection.find():
	pprint.pprint(document)
    
# query문의 조건에 해당하는 document들만을 반환
for document in collection.find({"author":"ktx"})
	pprint.pprint(document)

 

  • document counting
    • query를 사용한다.
print(collection.count_documents({}))

print(collection.count_documents({"author":"ktx"}))

 

4. Comparision query(비교)

  • data sample
# data set
daughter = {
	"name" : "lhb",
    "age" : 24,
    "weight" : 69,
    "tall" : 172,
    "insterest" : ["reading", "data science"],
    "birth" : datetime.datetime(2001,10,31),
    "gender" : "female"
}

mother = {
	"name" : "shj",
    "age" : 58,
    "weight" : 55,
    "tall" : 159,
    "insterest" : ["gaming", "breaking"],
    "birth" : datetime.datetime(1967,09,26),
    "gender" : "female"
}

father = {
	"name" : "lws",
    "age" : 59,
    "weight" : 79,
    "tall" : 182,
    "insterest" : ["hiking", "excersize"],
    "birth" : datetime.datetime(1966,03,01),
    "gender" : "male"
}

son = {
	"name" : "ljh",
    "age" : 31,
    "weight" : 78,
    "tall" : 173,
    "insterest" : ["gaming", "singing"],
    "birth" : datetime.datetime(1994,02,26),
    "gender" : "male"
}
family = [father,mother,daughter,son]

 

  • DB, Collectino 연결
familyDB = client.familyDB
familyColl = familyDB.familyColl
familyColl.insert_many(family)

 

  • $eq selctor
    • 조건 : 이름이 lhb  => "$eq": 지정된 값과 같은 값을 일치시킨다.
pprint.pprint(familyColl.find_one({"$eq":"lhb"}))
    • 조건 : 이름이 lhb가 아님 => "$ne": 지정된 값과 같지 않은 모든 값을 찾는다. 
for document in familyColl.find({"name" : {"$ne":"lhb}}):
	pprint.pprint(document)

 

  • $gt selctor ($lt도 같은 문법이다.)
    • 조건 : age가 31세 초과 => "$gt": 지정된 값보다 큰 값을 일치시킨다. (<)
for document in familyColl.find({"age":{"$gt":31}})):
	pprint.pprint(document)

 

  • 조건 : age가 31세 이상 => "$gte": 지정된 값보다 크거나 같은 값을 일치시킨다. (<=)
for document in familyColl.find({"age":{"$gte":31}})):
	pprint.pprint(document)
  • $in, $nin selector
  • $and, $or selector
  • $not, $nor selctor

5. Element

  • $in selctor
  • $type selector

6. Evaluation

  • data sample
  • DB, Collection 연결 및 자료 insert

 

  • $expr

 

  • DB, Collectino, Data setting

 

  • $cond
  • $mod
  • $regex
  • $optinos

7. Array

  • DB, Collection, Data setting

 

  • $all
  • $elemMatch
  • size

8. Bitwise

  • DB, Collection, Data setting

 

  • $bitsAllClear
  • $bitsAllSet
  • $bitsAnyClear
  • $bitsAnySet