클라우드 컴퓨팅 & NoSQL/MongoDB

Python을 이용한 간단한 mongodb insert 예제

Terry Cho 2013. 5. 4. 00:09

Python을 이용한 간단한 mongodb insert 예제


1. easy_install.exe를 이용하여, mongodb python driver인 pymongo를 설치


2. 코드 작성

 connection얻고, db선택하고,collection(여기서는 users테이블) 선택하면되고,

 insert,update등은 기존 mongodb script와 유사함. 에러 처리는 아래와 같이 try,except 사용

import sys

import pymongo

 

connection = pymongo.MongoClient("mongodb://localhost")

db = connection.terrydb

users = db.users

 

doc = {'_id':'myid','firstname':'Terry','lastname':'Cho'}

 

try:

    users.insert(doc)

except:

     print "insert failed",sys.exc_info()[0]

 

 

3. insert 확인


그리드형