import pymongo
#连接mongodb需要使用里面的mongoclient,一般来说传入mongodb的ip和端口即可
#第一个参数为host,,第二个为ip.默认为27017,
client=pymongo.MongoClient(host=‘127.0.0.1‘,port=27017)
#这样就可以拿到一个客户端对象了
#另外MongoClient的第一个参数host还可以直接传MongoDB的连接字符串,以mongodb开头,
#例如:client = MongoClient(‘mongodb://localhost:27017/‘)可以达到同样的连接效果
# print(client)
###################指定数据库
db=client.test
#也可以这样写
# db=client[‘test‘]
##################指定集合
collections=db.student
#也可以这样写
# collections=db[‘student‘]
###################插入数据
# student={
# ‘id‘:‘1111‘,
# ‘name‘:‘xiaowang‘,
# ‘age‘:20,
# ‘sex‘:‘boy‘,
# }
#
# res=collections.insert(student)
# print(res)
#在mongodb中,每一条数据其实都有一个_id属性唯一标识,
#如果灭有显示指明_id,mongodb会自动产生yigeObjectId类型的_id属性
#insert执行后的返回值就是_id的值,5c7fb5ae35573f14b85101c0
#也可以插入多条数据
# student1={
# ‘name‘:‘xx‘,
# ‘age‘:20,
# ‘sex‘:‘boy‘
# }
#
# student2={
# ‘name‘:‘ww‘,
# ‘age‘:21,
# ‘sex‘:‘girl‘
# }
# student3={
# ‘name‘:‘xxx‘,
# ‘age‘:22,
# ‘sex‘:‘boy‘
# }
#
# result=collections.insertMany([student1,student2,student3])
# print(result)
#这边的返回值就不是_id,而是insertoneresult对象
#我们可以通过打印insert_id来获取_id
#insert方法有两种
#insert_one,insertMany,一个是单条插入,一个是多条插入,以列表形式传入
#也可以直接inset(),如果是单个就直接写,多个还是以列表的形式传入
###################查找 单条查找
# re=collections.find_one({‘name‘:‘xx‘})
# print(re)
# print(type(re))
#{‘_id‘: ObjectId(‘5c7fb8d535573f13f85a6933‘), ‘name‘: ‘xx‘, ‘age‘: 20, ‘sex‘: ‘boy‘}
# <class ‘dict‘>
#####################多条查找
# re=collections.find({‘name‘:‘xx‘})
# print(re)
# print(type(re))
# for r in re:
# print(r)
#结果是一个生成器,我们可以遍历里面的这个对象,拿到里面的值
# <pymongo.cursor.Cursor object at 0x000000000A98E630>
# <class ‘pymongo.cursor.Cursor‘>
# re=collections.find({‘age‘:{‘$gt‘:20}})
# print(re)
# print(type(re))
# for r in re:
# print(r)
# 在这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号$gt,意思是大于,键值为20,这样便可以查询出所有
# 年龄大于20的数据。
# 在这里将比较符号归纳如下表:
"""
符号含义示例
$lt小于{‘age‘: {‘$lt‘: 20}}
$gt大于{‘age‘: {‘$gt‘: 20}}
$lte小于等于{‘age‘: {‘$lte‘: 20}}
$gte大于等于{‘age‘: {‘$gte‘: 20}}
$ne不等于{‘age‘: {‘$ne‘: 20}}
$in在范围内{‘age‘: {‘$in‘: [20, 23]}}
$nin不在范围内{‘age‘: {‘$nin‘: [20, 23]}}
"""
#正则匹配来查找
# re = collections.find({‘name‘: {‘$regex‘: ‘^x.*‘}})
# print(re)
# print(type(re))
# for r in re:
# print(r)
# 在这里将一些功能符号再归类如下:
"""
符号含义示例示例含义
$regex匹配正则{‘name‘: {‘$regex‘: ‘^M.*‘}}name以M开头
$exists属性是否存在{‘name‘: {‘$exists‘: True}}name属性存在
$type类型判断{‘age‘: {‘$type‘: ‘int‘}}age的类型为int
$mod数字模操作{‘age‘: {‘$mod‘: [5, 0]}}年龄模5余0
$text文本查询{‘$text‘: {‘$search‘: ‘Mike‘}}text类型的属性中包含Mike字符串
$where高级条件查询{‘$where‘: ‘obj.fans_count == obj.follows_count‘}自身粉丝数等于关注数
"""
################计数
# count=collections.find({‘age‘:{‘$gt‘:20}}).count()
# print(count)
#################排序
# result=collections.find({‘age‘:{‘$gt‘:20}}).sort(‘age‘,pymongo.ASCENDING)
# print([re[‘name‘] for re in result])
########### 偏移,可能想只取某几个元素,在这里可以利用skip()方法偏移几个位置,比如偏移2,就忽略前2个元素,得到第三个及以后的元素。
# result=collections.find({‘age‘:{‘$gt‘:20}}).sort(‘age‘,pymongo.ASCENDING).skip(1)
# print([re[‘name‘] for re in result])
##################另外还可以用limit()方法指定要取的结果个数,示例如下:
# results = collections.find().sort(‘age‘, pymongo.ASCENDING).skip(1).limit(2)
# print([result[‘name‘] for result in results])
# 值得注意的是,在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,很可能会导致内存溢出,
# 可以使用类似find({‘_id‘: {‘$gt‘: ObjectId(‘593278c815c2602678bb2b8d‘)}}) 这样的方法来查询,记录好上次查询的_id。
################################数据更新
# 对于数据更新要使用update方法
# condition={‘name‘:‘xx‘}
# student=collections.find_one(condition)
# student[‘age‘]=100
# result=collections.update(condition,student)
# print(result)
# 在这里我们将name为xx的数据的年龄进行更新,首先指定查询条件,然后将数据查询出来,修改年龄,
# 之后调用update方法将原条件和修改后的数据传入,即可完成数据的更新。
# {‘ok‘: 1, ‘nModified‘: 1, ‘n‘: 1, ‘updatedExisting‘: True}
# 返回结果是字典形式,ok即代表执行成功,nModified代表影响的数据条数。
# 另外update()方法其实也是官方不推荐使用的方法,在这里也分了update_one()方法和update_many()方法,用法更加严格,
# 第二个参数需要使用$类型操作符作为字典的键名,我们用示例感受一下。
# condition={‘name‘:‘xx‘}
# student=collections.find_one(condition)
# print(student)
# student[‘age‘]=112
# result=collections.update_one(condition,{‘$set‘:student})
# print(result)
# print(result.matched_count,result.modified_count)
#再看一个例子
# condition={‘age‘:{‘$gt‘:20}}
# result=collections.update_one(condition,{‘$inc‘:{‘age‘:1}})
# print(result)
# print(result.matched_count,result.modified_count)
# 在这里我们指定查询条件为年龄大于20,
# 然后更新条件为{‘$inc‘: {‘age‘: 1}},执行之后会讲第一条符合条件的数据年龄加1。
# <pymongo.results.UpdateResult object at 0x000000000A99AB48>
# 1 1
# 如果调用update_many()方法,则会将所有符合条件的数据都更新,示例如下:
condition = {‘age‘: {‘$gt‘: 20}}
result = collections.update_many(condition, {‘$inc‘: {‘age‘: 1}})
print(result)
print(result.matched_count, result.modified_count)
# 这时候匹配条数就不再为1条了,运行结果如下:
# <pymongo.results.UpdateResult object at 0x10c6384c8>
# 3 3
# 可以看到这时所有匹配到的数据都会被更新。
# ###############删除
# 删除操作比较简单,直接调用remove()方法指定删除的条件即可,符合条件的所有数据均会被删除,示例如下:
# result = collections.remove({‘name‘: ‘Kevin‘})
# print(result)
# 运行结果:
# {‘ok‘: 1, ‘n‘: 1}
# 另外依然存在两个新的推荐方法,delete_one()和delete_many()方法,示例如下:
# result = collections.delete_one({‘name‘: ‘Kevin‘})
# print(result)
# print(result.deleted_count)
# result = collections.delete_many({‘age‘: {‘$lt‘: 25}})
# print(result.deleted_count)
# # 运行结果:
# <pymongo.results.DeleteResult object at 0x10e6ba4c8>
# 1
# 4
# delete_one()即删除第一条符合条件的数据,delete_many()即删除所有符合条件的数据,返回结果是DeleteResult类型,
# 可以调用deleted_count属性获取删除的数据条数。
# 更多
# 另外PyMongo还提供了一些组合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),
# 就是查找后删除、替换、更新操作,用法与上述方法基本一致。
原文:https://www.cnblogs.com/tjp40922/p/10486317.html