2012年6月20日水曜日

Python + MongoDBの使い方

PyMongoというモジュールを使うとPython上からカンタンにMongoDBが使える。

#!/user/bin/python
# -*- coding: utf-8 -*-

from pymongo import Connection

conn = Connection('localhost')
# conn = Connection('xxx.xxx.xxx.xxx', 27017)

#db - collection - {key1:value1, key2, value2, "_id":ObjcetId("~")}
db = conn['test']

col = db['entry']

# Insert 10 objects
# This may create duplicate entries
for i in range(0,10):
        col.insert({'num1': i, 'num2': i*i})

# Print all
for data in col.find():
        print data

# Print where 'num1' is 5
for data in col.find({'num1': 5}):
        print data
        
# Delete something
col.remove({'num1': 5})
        
# Update something
target = col.find_one({'num1': 9})
target['num1'] = 99
col.save(target)

for data in col.find():
        print data

conn.disconnect()

こんなかんじ。

0 件のコメント:

コメントを投稿