2016年8月4日木曜日

開発環境

MongoDB and Python: Patterns and processes for the popular document-oriented database (Niall O'Higgins (著)、 O'Reilly Media)のChapter 3.(Common MongoDB and Python Patterns)の A Uniquely Document-Oriented Pattern: Embedding を 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

import pprint


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

    def p():
        for i, user_doc in enumerate(dbh.users.find()):
            # print('{0}: {1}'.format(i, user_doc))
            pprint.pprint(user_doc)

    dbh.users.delete_many({'username': 'foouser'})
    user_doc = {
        'username': 'foouser',
        'emails': [
            {
                'email': 'foouser1@example.com',
                'primary': True
            },
            {
                'email': 'foouser2@example2.com',
                'primary': False
            },
            {
                'email': 'foouser3@example3.com',
                'primary': False
            }
        ]
    }
    dbh.users.delete_many({'emails.email': 'foouser1@example.com'})
    dbh.users.insert_one(user_doc)
    p()

    user_doc_result = dbh.users.find_one(
        {'emails.email': 'foouser1@example.com'})
    assert user_doc == user_doc_result

    del user_doc_result['emails'][1]
    dbh.users.update_one(
        {'username': 'foouser'},
        {'$set': {'emails': user_doc_result['emails']}})
    p()

    dbh.users.update_one(
        {'username': 'foouser'},
        {'$pull': {'emails': {'email': 'foouser3@example3.com'}}})
    p()

    dbh.users.update_one(
        {'username': 'foouser'},
        {'$pull': {'emails': {'primary': {'$ne': True}}}})
    p()

    new_email = {'email': 'foouser4@example4.com', 'primary': False}
    dbh.users.update_one({'username': 'foouser'},
                         {'$push': {'emails': new_email}})
    p()

    dbh.users.update_one({'emails.email': 'foouser4@example4.com'},
                         {'$set': {'emails.$.primary': True}})
    p()
    dbh.users.update_one({'emails.email': 'foouser1@example.com'},
                         {'$set': {'emails.$.primary': False}})
    p()

if __name__ == '__main__':
    main()

入出力結果(Terminal, IPython)

$ ./sample1.py
Connected successfully
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True},
            {'email': 'foouser2@example2.com', 'primary': False},
            {'email': 'foouser3@example3.com', 'primary': False}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True},
            {'email': 'foouser3@example3.com', 'primary': False}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True},
            {'email': 'foouser4@example4.com', 'primary': False}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': True},
            {'email': 'foouser4@example4.com', 'primary': True}],
 'username': 'foouser'}
{'_id': ObjectId('57a2f49ea54d751493f614b7'),
 'emails': [{'email': 'foouser1@example.com', 'primary': False},
            {'email': 'foouser4@example4.com', 'primary': True}],
 'username': 'foouser'}
 $

0 コメント:

コメントを投稿