설치
pip install pymongo
easy_install pymongo
접속
from pymongo import MongoClient #모듈 추가
client = MongoClient('mongodb://user:password@localhost:27017/') #auth설정을 False로 한경우 user,passwd는 안써도 된다.
db = client["test"] #use test (실행)
collection = db["collection"] #colletion 선택
Query
db.collection_names(include_system_collections=False) #collection명 얻어오기
collection.insert_one(json_var) #한개의 Docment만 입력
collection.insert_many(json_var) #Bulk insert (여러개의 Document 입력)
#json_var에 _id가 있는 경우는 해당 값을 id로 사용하지만 없는경우에는 .inserted_id 를 마지막에 붙여서 자동으로 만들 수 있도록 한다.
collection.find_one( {"name" : "lukomen"} ) #조건에 만족하는 한개의 결과를 리턴
collection.find( {"name" : "lukomen"} ) #조건에 만족하는 모든 결과 리턴
collection.find().count() #전체 문서의 개수 리턴
collection.find( {"name" : "lukomen"} ).count() #조건에 만족하는 결과 개수 리턴
그외 다양한 방식으로 날리는 find쿼리는 여기를 참조
map/reduce
map/reduce작업을 위해서는 모듈을 하나 더 import시키고 map과 reduce function을 작성해서 map_reduce(map_func, reduce_func, colle에 인자로 넣어준다.
from bsn.code impport Code
mapper = Code("""
function () {
this.tags.forEach(function(z) {
emit(z, 1);
});
}
""")
reducer = Code("""
function (key, values) {
var total = 0;
for (var i = 0; i < values.length; i++) {
total += values[i];
}
return total;
}
""")
result = db.things.map_reduce(mapper, reducer, "myresults")
for doc in result.find():
print doc
group
SQL의 group by 문과 비슷한 역활을 map/reduce를 통해 진행 할 수 있다.
from bson.code import Code
reducer = Code("""
function(obj, prev){
prev.count++;
}
""")
results = db.things.group(key={"x":1}, condition={}, initial={"count": 0}, reduce=reducer)
for doc in results:
print doc
결과는 아래와 같이 나온다고 가정할 수 있다. x가
{u'count': 1.0, u'x': 1.0} #1일때 1개
{u'count': 2.0, u'x': 2.0} #2일때 2개
{u'count': 1.0, u'x': 3.0} #3일때 1개 뭐 이런식
'python' 카테고리의 다른 글
[Django] Createsuperuser 시 에러 발생 (0) | 2018.11.09 |
---|