安装
pip install pymongo
python3.4环境配置好,我是Windows系统,cmd命令安装就可以了
连接数据库,简单增加,查询数据
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
client = MongoClient('localhost', 27017)
db = client.PymongoDemo
"""第二种连接方法"""
#client = MongoClient('mongodb://localhost:27017/')
#db = client['test-database']
#collection = db['test-collection']
post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
posts = db.posts
"""要插入到文档的集合,我们可以使用insert_one()方法:"""
post_id = posts.insert_one(post).inserted_id
print(post_id)
"""我们列出数据库所有的集合"""
db.collection_names(include_system_collections=False)
print(posts.find_one())
print(posts.find_one({"author": "Mike"}))
print(posts.find_one({"author": "Eliot"}))
#根据ObjectId查询
posts.find_one({"_id": post_id})
"""在Web应用程序中的一个常见的任务是让从请求的URL获得ObjectId来查找匹配的文件。
在这种情况下,有必要将其传递给find_one前,从一个字符串转换成ObjectId:"""
def get(post_id):
document = client.db.collection.find_one({'_id': ObjectId(post_id)})
批量插入
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
client = MongoClient('localhost', 27017)
db = client.PymongoDemo
posts = db.posts
#批量插入
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)
print(result.inserted_ids)
查询
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
client = MongoClient('localhost', 27017)
db = client.PymongoDemo
posts = db.posts
for post in posts.find():
print(post)
for post in posts.find({"author": "Mike"}):
print(post)
#统计
print(posts.count())
"""范围查询"""
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
print(post)
"""索引"""
"""创建唯一索引"""
"""一种是在_id的索引MongoDB的自动创建,另一种是我们刚创建的用户ID的索引。"""
#result = db.profiles.create_index([('user_id', pymongo.ASCENDING)], unique=True)
#print(list(db.profiles.index_information()))
user_profiles = [
{'user_id': 211, 'name': 'Luke'},
{'user_id': 212, 'name': 'Ziltoid'}]
result = db.profiles.insert_many(user_profiles)
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) #报错