import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')#连接数据库
db = client.test #等价于client['test'],创建test数据库
#指定集合
collection = db.students #等价于db['students']
#插入数据
student = {
"id":"20170101",
"name":"Jorden",
"age":20,
"gender":"male"
}
# result = collection.insert_one(student)
# # result = collection.insert_many([student1,student2])
# # print(result.inserted_ids)
# print(result.inserted_id)
#查询
# Query_result = collection.find_one({'name':'Jorden'})
# print(type(Query_result))
# print(Query_result)
# <class 'dict'>
# {'_id': ObjectId('623dbe2bcfbd0be74da88977'), 'id': '20170101', 'name': 'Jorden', 'age': 20, 'gender': 'male'}
#查询多条数据用find(),返回生成器对象,结果遍历
# Query_result = collection.find({'age':{'$gt':20}) 查询条件大于20
# Query_result = collection.find({'name':{'$regex':'^M.*'}) 匹配以M开头的正则表达式
#计数
# count = collection.count_documents({'name':'Jorden'})
# print(count)
#排序
# results = collection.find().sort('name',pymongo.ASCENDING)
# print([result['name'] for result in results])
# ['Jorden']
#偏移
# results = collection.find().sort('name',pymongo.ASCENDING).skip(2)#偏移两个,从第三个开始取
# results = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2)#偏移两个,从第三个开始取,取两个
"""数据量很大的时候,不用大偏移量查询,会导致内存溢出"""
# from bson import ObjectId
# collection.find({"_id":{'$gt':ObjectId('***********************')}})取大于的值
#更新
# condition= {'name':'Jorden'}
# student = collection.find_one(condition)
# student['age']= 25
# result_ = collection.update_one(condition,{'$set':student})#指定更新的条件和更新后的数据
# '$inc':{'age':1} age+1
# print(result_)
# print(result_.matched_count,result_.modified_count)
# <pymongo.results.UpdateResult object at 0x00000177B517E340>
# 1 0
#删除
result_ = collection.delete_one({'name':'Jorden'})
print(result_)
print(result_.deleted_count)
#其他操作
# collection.find_one_and_delete()
# collection.find_one_and_replace()
# collection.find_one_and_update()
pymongo 基础操作
最新推荐文章于 2025-08-29 09:35:08 发布
本文将介绍如何使用Python的pymongo库连接MongoDB数据库,进行基本的数据增删查改操作,包括连接数据库、创建集合、插入文档、查询数据、更新记录和删除记录等核心功能。

1395

被折叠的 条评论
为什么被折叠?



