from pymongo import MongoClient
client = MongoClient(host='127.0.0.1', port=27017)
collection = client[database_name][collection_name]
通过以上代码可以获取到 MongoDB 在数据库中存储的集合(collection),
以下函数均为collection可直接调用的方法
bulk_write(requests, ordered=True,):
对数据库采取一系列操作,比如 InsertOne, UpdateOne, UpdateMany, ReplaceOne, DeleteOne, Deletemany
for doc in db.test.find({}):
print(doc)
# 输出
# {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
# {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
# DeleteMany, UpdateOne, and UpdateMany are also available.
from pymongo import InsertOne, DeleteOne, ReplaceOne
requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}),
ReplaceOne({'w': 1}, {'z': 1}, upsert=True)]
result = db.test.bulk_write(requests)
result.inserted_count
# 输出
# 1
result.deleted_count
# 输出
# 1
result.modified_count
# 输出
# 0
result.upserted_ids
# 输出
# {2: ObjectId('54f62ee28891e756a6e1abd5')}
for doc in db.test.find({}):
print(doc)
# 输出
# {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
# {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
# {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
insert_one(document,):
添加一个文档
insert_many(documents,ordered=True,):
添加多个文档组成的可迭代对象
replace_one(filter, replacement,upsert=False,):
根据过滤条件替换数据
Notice:将参数 upsert 设置为 True时,如果满足过滤条件的文档不存在,replacement将作为新文档插入
update_one(filter, update, upsert=False,):
更新满足过滤条件的第一个文档
Notice:如果 upsert 为True,如果没有文档满足过滤条件,文档将作为新文档插入
update_many(filter, update, upsert=False,):
更新满足过滤条件的所有文档
Notice:如果 upsert 为True,如果没有文档满足过滤条件,文档将作为新文档插入
delete_one(filter, ):
删除满足过滤条件的第一个文档
delete_many(filter, ):
删除满足过滤条件的所有文档
aggregate(pipeline,):
对该集合内的数据进行聚合,用法和MongoDB Server的aggregate函数一样
pipeline:由 $group, $match, $project, $unwind, $sort 等聚合函数组成的列表
from pymongo import MongoClient
from pprint import pprint
db = MongoClient().aggregation_example
result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
{"x": 2, "tags": ["cat"]},
{"x": 2, "tags": ["mouse", "cat", "dog"]},
{"x": 3, "tags": []}])
pipeline = [{"$unwind": "$tags"},
{"$group": {"_id": "$tags", "count": {"$sum": 1}}},
{"$sort": dict([("count", -1), ("_id", -1)])}]
pprint(list(db.things.aggregate(pipeline)))
# 查看聚合的详细信息
db.command('aggregate', 'things', pipeline=pipeline, explain=True)
collection.drop():
删除该集合
count_documents(filter,):
返回满足过滤条件的文档的数量
create_index(key,):
为集合在字段key上创建一个索引
# 使用多个字段创建索引
my_collection.create_index([
("mike", pymongo.DESCENDING),
("eliot", pymongo.ASCENDING)
],background=True,name='user_name')
drop_index(index_name,):
删除集合中已经存在的索引
drop_indexes():
删除集合中所有的索引(_id字段不会删除)
reindex():
更新所有索引(该操作会阻断其他操作)
list_indexes():
以PyMongo游标的形式返回该集合所有的索引,
index_information():
以字典的形式返回该集合上的索引的相关信息
distinct(key, filter=None,):
返回在满足过滤条件的文档中,所有key的取值
drop():
删除该集合,drop_collection()的别名
find_one(filter=None,projection=None,):
返回满足过滤条件的第一个文档
find(filter=None, projection=None,skip=0,limit=0,sort=None,):
返回满足过滤条件的所有文档组成的 PyMongo 游标(类似于Python的生成器)
find_one_and_delete(filter,projection=None,):
删除满足过滤条件的第一个文档,并将删除的文档返回
list_collections():
返回一个类似于生成器的 Pymongo 游标,包含该数据库所有的集合
list_collection_names():
返回一个列表,包含该数据里所有的集合
map_reduce():
在该集合上使用map/reduce操作
options():
以字典的形式返回该集合的各项参数(使用create_index()创建集合时,指定的参数)
rename(new_name,):
重命名该集合
skip(N):
跳过返回的前N个文档
sort(key,direction=pymongo.ASCENDING):
对返回的文档进行排序,参数direction必须为pymongo.ASCENDING或者pymongo.DESCENDING
db.command():
向MongoDB服务器发出指令
db.command("serverStatus"):
返回MongoDB 服务器的状态
db.command("dbstats"):
返回该数据库的统计信息
弃用的函数
group(key,):建议使用aggragate()和$group代替
count(): 建议使用count_documents()或estimated_document_count()代替
insert():建议使用insert_one()或insert_many()代替
save():建议使用insert_one()或replace_one()代替
update():建议使用replace_one(),update_one()或update_many()代替
remove():建议使用delete_one(),delete_many()代替
find_and_modify():建议使用find_one_and_delete(),find_one_and_replace()代替
ensure_index():建议使用create_index()代替