開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
- MongoDB (NoSQL, データベース)
MongoDB and Python: Patterns and processes for the popular document-oriented database (Niall O'Higgins (著)、 O'Reilly Media)のChapter 2.(Reading and Writing to MongoDB with Python)の Inserting a Document into a Collection を Python 2.7 ではなく Python 3.5 で取り組んでみる。(2.7と3では、pymongo module が少し変わったみたい。)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import datetime
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
def main():
try:
c = MongoClient(host="localhost", port=27017)
print('Connected successfully')
except ConnectionFailure as err:
print('Could not connect to MongoDB: {0}'.format(err), file=sys.stderr)
sys.exit(1)
dbh = c['mydb']
assert dbh.client == c
user_doc = dict(
username='janedoe',
firstname='Jane',
surname='Doe',
dateofbirth=datetime.datetime(1974, 4, 12),
email='janedoe74@example.com',
score=0
)
dbh.users.insert(user_doc)
print('Successfully inserted document: {0}'.format(user_doc))
if __name__ == '__main__':
main()
入出力結果(Terminal, IPython)
$ ./sample2.py Connected successfully Successfully inserted document: {'email': 'janedoe74@example.com', 'dateofbirth': datetime.datetime(1974, 4, 12, 0, 0), 'score': 0, 'username': 'janedoe', 'surname': 'Doe', 'firstname': 'Jane', '_id': ObjectId('57946f2aa54d75164f103be7')} $
0 コメント:
コメントを投稿