In [44]:
import datetime
import pymongo
from pprint import pprint
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['chriscoin']
users = db.blockchain
print(users.find_one())


{'nonce': '-', '_id': ObjectId('593166bf9be8fa000cce6fcd'), 'timestamp': datetime.datetime(2017, 6, 2, 13, 23, 11, 677000), 'miner_verify': True, 'cc_amount': 100, 'from_user_pk': '<miner>', 'to_user_pk': b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA71Y6cHSaTqNMlku3323o\nZe7AcsbGmXPX0W8e4FARkkinAd+k5J/ca1HTnwPrzWDPqkjpAAPvMK+Yht2J6hsT\nATmXG6eVi4Wb86qF7e8dJScQUsXkfr/lZ1DF7uPrQjVrlY60PXxclRyUcdw681kN\nwYZVDUuA6mZODpCQGoIBdH6sHbHJDb4QSRbQkHJMKkyoHucF6kjxlF9DAKQsp7dB\ntfimwpdTqtO5mQh0Bm/eUtFNGJRpnNLWiEUrjGwKBx50CYSskLnd3KDBaBkQSwkI\nwX+fMSApZLrlJMOQxLFSoUGtrJa52zCvaBde9HTz0TYVOmCTWybhp/7YzN7KuOux\n+QIDAQAB\n-----END PUBLIC KEY-----'}

In [2]:
db = client['test-database']
post = {
    "author": "Mike",
    "text": "My first blog post!",
    "tags": ["mongodb", "python", "pymongo"],
    "date": datetime.datetime.utcnow()
}

posts = db.posts
post_id = posts.insert_one(post).inserted_id
post_id


Out[2]:
ObjectId('5930f8103ea02959c9573204')

In [3]:
import pprint
pprint.pprint(posts.find_one())


{'_id': ObjectId('592ec79f3ea029696c8436ed'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 5, 31, 13, 39, 43, 100000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

In [4]:
posts.find_one({"author": "Eliot"})

In [5]:
pprint.pprint(posts.find_one({"_id": post_id}))


{'_id': ObjectId('592ec79f3ea029696c8436ed'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 5, 31, 13, 39, 43, 100000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

In [6]:
post_id_as_str = str(post_id)
posts.find_one({"_id": post_id_as_str})

In [7]:
new_posts = [
    {
        "author": "Mike",
        "text": "Another post!",
        "tags": ["bulk", "insert"],
        "date": datetime.datetime(2009, 11, 12 , 11, 14)
    },
    {
        "author": "Eliot",
        "title": "MongoDB is fun",
        "text": "and pretty easy too!",
        "date": datetime.datetime(2009, 11, 10 , 10, 45)
    }
]

result = posts.insert_many(new_posts)
result.inserted_ids


Out[7]:
[ObjectId('592ec79f3ea029696c8436ee'), ObjectId('592ec79f3ea029696c8436ef')]

In [8]:
for post in posts.find():
    pprint.pprint(post)


{'_id': ObjectId('592ec79f3ea029696c8436ed'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 5, 31, 13, 39, 43, 100000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
{'_id': ObjectId('592ec79f3ea029696c8436ee'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}
{'_id': ObjectId('592ec79f3ea029696c8436ef'),
 'author': 'Eliot',
 'date': datetime.datetime(2009, 11, 10, 10, 45),
 'text': 'and pretty easy too!',
 'title': 'MongoDB is fun'}

In [9]:
posts.count()


Out[9]:
3

In [10]:
posts.find({"author": "Mike"}).count()


Out[10]:
2

In [11]:
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
    pprint.pprint(post)


{'_id': ObjectId('592ec79f3ea029696c8436ef'),
 'author': 'Eliot',
 'date': datetime.datetime(2009, 11, 10, 10, 45),
 'text': 'and pretty easy too!',
 'title': 'MongoDB is fun'}
{'_id': ObjectId('592ec79f3ea029696c8436ee'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}

In [26]:
result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],
                                 unique=True)
sorted(list(db.profiles.index_information()))


Out[26]:
['_id_', 'user_id_1']

In [27]:
user_profiles = [
    {'user_id': 211, 'name': 'Luke'},
    {'user_id': 212, 'name': 'Ziltoid'}
]
result = db.profiles.insert_many(user_profiles)


---------------------------------------------------------------------------
BulkWriteError                            Traceback (most recent call last)
<ipython-input-27-d4dfa39ab03a> in <module>()
      3     {'user_id': 212, 'name': 'Ziltoid'}
      4 ]
----> 5 result = db.profiles.insert_many(user_profiles)

/usr/local/lib/python3.5/dist-packages/pymongo/collection.py in insert_many(self, documents, ordered, bypass_document_validation)
    709         blk = _Bulk(self, ordered, bypass_document_validation)
    710         blk.ops = [doc for doc in gen()]
--> 711         blk.execute(self.write_concern.document)
    712         return InsertManyResult(inserted_ids, self.write_concern.acknowledged)
    713 

/usr/local/lib/python3.5/dist-packages/pymongo/bulk.py in execute(self, write_concern)
    491                 self.execute_no_results(sock_info, generator)
    492             elif sock_info.max_wire_version > 1:
--> 493                 return self.execute_command(sock_info, generator, write_concern)
    494             else:
    495                 return self.execute_legacy(sock_info, generator, write_concern)

/usr/local/lib/python3.5/dist-packages/pymongo/bulk.py in execute_command(self, sock_info, generator, write_concern)
    329                 full_result['writeErrors'].sort(
    330                     key=lambda error: error['index'])
--> 331             raise BulkWriteError(full_result)
    332         return full_result
    333 

BulkWriteError: batch op errors occurred

In [28]:
new_profile = {'user_id': 213, 'name': 'Drew'}
duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
result = db.profiles.insert_one(new_profile)
result = db.profiles.insert_one(duplicate_profile)


---------------------------------------------------------------------------
DuplicateKeyError                         Traceback (most recent call last)
<ipython-input-28-90fcf5ba1355> in <module>()
      1 new_profile = {'user_id': 213, 'name': 'Drew'}
      2 duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
----> 3 result = db.profiles.insert_one(new_profile)
      4 result = db.profiles.insert_one(duplicate_profile)

/usr/local/lib/python3.5/dist-packages/pymongo/collection.py in insert_one(self, document, bypass_document_validation)
    655             return InsertOneResult(
    656                 self._insert(sock_info, document,
--> 657                              bypass_doc_val=bypass_document_validation),
    658                 self.write_concern.acknowledged)
    659 

/usr/local/lib/python3.5/dist-packages/pymongo/collection.py in _insert(self, sock_info, docs, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val)
    560             return self._insert_one(
    561                 sock_info, docs, ordered,
--> 562                 check_keys, manipulate, write_concern, op_id, bypass_doc_val)
    563 
    564         ids = []

/usr/local/lib/python3.5/dist-packages/pymongo/collection.py in _insert_one(self, sock_info, doc, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val)
    542                 codec_options=self.__write_response_codec_options,
    543                 check_keys=check_keys)
--> 544             _check_write_command_response([(0, result)])
    545         else:
    546             # Legacy OP_INSERT.

/usr/local/lib/python3.5/dist-packages/pymongo/helpers.py in _check_write_command_response(results)
    312             error["index"] += offset
    313             if error.get("code") == 11000:
--> 314                 raise DuplicateKeyError(error.get("errmsg"), 11000, error)
    315             raise WriteError(error.get("errmsg"), error.get("code"), error)
    316         else:

DuplicateKeyError: E11000 duplicate key error collection: test-database.profiles index: user_id_1 dup key: { : 213 }

In [49]:
users = db.users
result = db.users.create_index([('username', pymongo.ASCENDING)],
                                 unique=True)

In [54]:
new_user = {
    'username': 'Alice',
    'password': 'password'
}

users.insert_one(new_user)


Out[54]:
<pymongo.results.InsertOneResult at 0x7f5545454558>

In [57]:
# for user in users.find():
#     pprint.pprint(type(user))

user = users.delete_many({'username': 'Alice'})

In [12]:
for user in users.find():
    pprint.pprint(user)

In [11]:
user = users.find_one({'username': 'Alice'})
print(user)


None

In [20]:
db = client['chriscoin_database']
users = db.users

In [21]:
print(users.find_one())


None

In [ ]: