2016年7月30日土曜日

開発環境

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)の Deleting Documents from a Collection を Python 2.7 ではなく Python 3.5 で取り組んでみる。(2.7と3では、pymongo module が少し変わったみたい。)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
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_docs = dbh.users.find()
    for user in user_docs:
        print('username: {username}, score: {score}'.format(**user))

    dbh.users.update_one({'username': 'janedoe'}, {'$set': {'score': 1}})

    old_user_doc = dbh.users.find({'score': 1})
    print('score 1: {0}'.format(dbh.users.count({'score': 1})))
    for user in old_user_doc:
        print('{username}: {score}'.format(**user))

    result = dbh.users.delete_one({'score': 1})
    print('deleted: {0}'.format(result.deleted_count))
    print('score 1: {0}'.format(dbh.users.count({'score': 1})))
    new_user_doc = dbh.users.find({'score': 1})
    for user in new_user_doc:
        print('{username}: {score}'.format(**user))

if __name__ == '__main__':
    main()

入出力結果(Terminal, IPython)

$ ./sample4.py
Connected successfully
username: janedoe, score: 1
score 1: 1
janedoe: 1
deleted: 1
score 1: 0
$

0 コメント:

コメントを投稿

Comments on Google+: