爬虫Day17-MongoDb数据存取

2018-12-07  本文已影响0人  黄yy家的jby

摘要

导入模块

import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
#client = pymongo.MongoClient('mongodb://localhost:27017')
db = client.test    
db = client['test']     
collection = db.student     
collention = db['student']

增加数据

student ={
        'id':'20170101',
        'name':'Jordan',
        'age':20,
        'gender':'male'
        }
result = collection.insert_one(student)
student_1 ={
        'id':'201710080',
        'name':'guoguo',
        'age':23,
        'gender':'female'
        }
student_2 ={
        'id':'201710086',
        'name':'smwolf',
        'age':25,
        'gender':'male'
        }
result = collection.insert_many([student_1,student_2])

删除数据

result = collection.remove_one({'name':'guoguo'})
result = collection.remove_many('{age':25})

改变数据

condition={'name':'guoguo'}
result=collection.update(condition,'age':25)

查找数据

result=collection.find_one({'name':'guoguo'})

results=collection.find_many({'age':20})
for result in results:
    print(result)
#find_many返回的是类似列表的东西,需要遍历取到

results=collection.find({'age':{'$gt':20}})   #年龄大于20
results=collection.find({'name':{'$regex':'G.*'}})  #支持正则表达式,name是以G开头

计数及排序

count = collection.find(...).count()   #计数
results = collection.find().sort('name',pymongo.ASCENDING)  #按照升序排列
上一篇 下一篇

猜你喜欢

热点阅读