Examples from: http://api.mongodb.com/python/current/tutorial.html
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())
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]:
In [3]:
import pprint
pprint.pprint(posts.find_one())
In [4]:
posts.find_one({"author": "Eliot"})
In [5]:
pprint.pprint(posts.find_one({"_id": post_id}))
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]:
In [8]:
for post in posts.find():
pprint.pprint(post)
In [9]:
posts.count()
Out[9]:
In [10]:
posts.find({"author": "Mike"}).count()
Out[10]:
In [11]:
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
pprint.pprint(post)
In [26]:
result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],
unique=True)
sorted(list(db.profiles.index_information()))
Out[26]:
In [27]:
user_profiles = [
{'user_id': 211, 'name': 'Luke'},
{'user_id': 212, 'name': 'Ziltoid'}
]
result = db.profiles.insert_many(user_profiles)
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)
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]:
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)
In [20]:
db = client['chriscoin_database']
users = db.users
In [21]:
print(users.find_one())
In [ ]: