# 导入模块
import pymongo
# 建立MongoClient连接,需先启动已经安装的mongodb服务
client = MongoClient('localhost', 27017)
# 或者 client = MongoClient('mongodb://localhost:27017')
# 进入数据库
db = client.test_database
# 或者 db = client['test_database']
# 进入集合
collection = db.test_collection
# 或者collection = db['test_collection']
# 插入文档,MongoDB中的数据使用的是类似Json风格的文档
import datetime
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
# 查找一条数据
posts.find_one()
posts.find_one({"author":"Mike"})
posts.find_one({"author":"Eliot"})
# 通过ObjectID查找
posts.find_one({"_id":post_id})
# 不要转化ObjectID的类型为String
post_id_as_str = str(post_id)
posts.find_one({"_id":post_id_as_str}) # No result
from bson.objectid import ObjectID
def get(post_id):
document = client.db.collection.find_one({"_id":ObjectId(post_id)})
# 多条插入
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
# 查找多条数据
for post in posts.find():
print(post)
# 约束条件查找
for post in posts.find({"author":"Mike"})
print(post)
# 获取集合的数据条数
posts.count()
posts.find({"author":"Mike"}).count()
# 范围查找
d = datetime.datetime(2010, 10, 10, 10)
for post in posts.find({"date":{"$lt":d}}).sort("author"):
print(post)
# 建立索引
from pymongo import ASCENDING, DESCENDING
posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
# 连接聚集
account = db.Account # 或者 account = db["Account"]
# 查看全部聚集名称
db.collection_names()
# 查看聚集的一条记录
db.Account.find_one()
db.Account.find_one({"UserName":"keyword"})
# 查看聚集的字段
db.Account.find_one({},{"UserName":1,"Email":1})
db.Account.find_one({},{"UserName":1,"Email":1,"_id":0})
# 查看聚集的多条记录
for item in db.Account.find():
print(item)
for item in db.Account.find({"UserName":"libing"}):
print(item["UserName"])
# 查看聚集的记录统计
db.Account.find().count()
db.Account.find({"UserName":"keyword"}).count()
# 聚集查询结果排序
db.Account.find().sort("UserName") # 默认为升序
db.Account.find().sort("UserName",pymongo.DESCENDING) # 降序
db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)]) # 多结果排序
# 添加记录
db.Account.insert({"AccountID":21,"UserName":"libing"})
# 修改记录
db.Account.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
# 删除记录
db.Account.remove() # 全部删除
db.Test.remove({"UserName":"keyword"})