2.3 在collection中添加document
import pymongo
myclient = pymongo.MongoClient(“mongodb://localhost:27017”) # Host以及port
db = myclient[“myDatabase”]
coll = db[“collection1”]
dict = {“name”: “liming”, “age”: “20”}
x = coll.insert_one(dict)
1
2
3
4
5
6
7
如果想要插入多条数据,需要使用insert_many()函数
import pymongo
myclient = pymongo.MongoClient(“mongodb://localhost:27017”) # Host以及port
db = myclient[“myDatabase”]
coll = db[“collection1”]
mylist = [
{ “name”: “hanmei”, “age”: “19” },
{ “name”: “wanghua”, “alexa”: “18” },
{ “name”: “lihong”, “alexa”: “20” }
]
y = coll.insert_many(mylist)
import requests
from bs4import BeautifulSoup
import pymongo
url =‘http://news.sina.com.cn/china/’
res = requests.get(url)# 使用get方法请求url
res.encoding =‘utf-8’ # 将编码格式设置为utf-8
soup = BeautifulSoup(res.text, ‘html.parser’)
client = pymongo.MongoClient(‘localhost’, 27017)# 创建连接,因为用的本机的mongodb数据库,所以直接写localhost即可,也可以写成127.0.0.1,27017为端口
db = client[‘mydb’]# 连接的数据库
collection = db[‘my_collection’]# 连接的表
for newsin soup.select(‘.news-item’):#查找出class内容含news-item的,并使用循环遍历每一个
if len(news.select('h2')) >0 :# 判断标题是否为空,不为空时做详细处理
h2 = news.select('h2')[0].text# 获取新闻的标题,并赋值给变量h2
time = news.select('.time')[0].text# 获取标题的时间,并赋值给time
url = news.select('a')[0]['href']# 获取标题的url,并赋值给url
data = {'title': h2, 'time': time, 'url':url}# 将数据存入到字典变量data中
collection.insert(data)# 将data中的输入插入到mongodb数据库
实际上,在PyMongo 3.x版本中,官方已经不推荐使用insert()方法了。当然,继续使用也没有什么问题。官方推荐使用insert_one()和insert_many()方法来分别插入单条记录和多条记录,示例如下:
student = {
‘id’: ‘20170101’,
‘name’: ‘Jordan’,
‘age’: 20,
‘gender’: ‘male’
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)
复制
运行结果如下:
<pymongo.results.InsertOneResult object at 0x10d68b558>
5932ab0f15c2606f0c1cf6c5
复制
与insert()方法不同,这次返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id。
对于insert_many()方法,我们可以将数据以列表形式传递,示例如下:
student1 = {
‘id’: ‘20170101’,
‘name’: ‘Jordan’,
‘age’: 20,
‘gender’: ‘male’
}
student2 = {
‘id’: ‘20170202’,
‘name’: ‘Mike’,
‘age’: 21,
‘gender’: ‘male’
}
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
复制
运行结果如下:
<pymongo.results.InsertManyResult object at 0x101dea558>
[ObjectId(‘5932abf415c2607083d3b2ac’), ObjectId(‘5932abf415c2607083d3b2ad’)]
复制
该方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表。
mongodb本地插入数据的基本操作
#!/usr/bin/env python
#-- coding:utf-8 --
“”“在python脚本中,将文件导入到数据库中
“””
from pymongo import MongoClient
MONGO_URL = “mongodb://localhost:27017” #how to hnow
MONGO_DB = “test”
MONGO_TABLE = “day1”
client = MongoClient(MONGO_URL) # 生成mongodb对象
db = client[MONGO_DB]
定义插入数据的函数
def save_to_mongo(data):
if db[MONGO_TABLE].insert(data):
print(“成功储存到MongoDB”, data)
return True
return False
data = {‘name’:‘mike’, ‘score’:99}
save_to_mongo(data)
2.使用csv中的DictReader函数读取
#!/usr/bin/env python
-- coding: utf-8 --
@Time : 2018/10/21 11:31
@Author : deli Guo
@Site :
@File : csv文件存入mongoDB.py
@Software : PyCharm
导包
from pymongo import MongoClient
import csv
创建连接MongoDB数据库函数
def connection():
# 1:连接本地MongoDB数据库服务
conn=MongoClient(“localhost”)
# 2:连接本地数据库(guazidata)。没有时会自动创建
db=conn.guazidata
# 3:创建集合
set1=db.data
# 4:看情况是否选择清空(两种清空方式,第一种不行的情况下,选择第二种)
#第一种直接remove
set1.remove(None)
#第二种remove不好用的时候
# set1.delete_many({})
return set1
def insertToMongoDB(set1):
# 打开文件guazi.csv
with open(‘guazi.csv’,‘r’,encoding=‘utf-8’)as csvfile:
# 调用csv中的DictReader函数直接获取数据为字典形式
reader=csv.DictReader(csvfile)
# 创建一个counts计数一下 看自己一共添加了了多少条数据
counts=0
for each in reader:
# 将数据中需要转换类型的数据转换类型。原本全是字符串(string)。
each[‘index’]=int(each[‘index’])
each[‘价格’]=float(each[‘价格’])
each[‘原价’]=float(each[‘原价’])
each[‘上牌时间’]=int(each[‘上牌时间’])
each[‘表显里程’]=float(each[‘表显里程’])
each[‘排量’]=float(each[‘排量’])
each[‘过户数量’]=int(each[‘过户数量’])
set1.insert(each)
counts+=1
print(‘成功添加了’+str(counts)+'条数据 ')
创建主函数
def main():
set1=connection()
insertToMongoDB(set1)
判断是不是调用的main函数。这样以后调用的时候就可以防止不会多次调用 或者函数调用错误
if name==‘main’:
main()
3.超详细的利用python操作MongoDB数据库
class MyMongoDB: #创建一个类
def init(self, database, collection): #利用初始化的方法输入要操作的数据库(database),集合(collection)
import pymongo #导入pymongo模块
self.connet = pymongo.MongoClient() #连接到虚拟机上的mongo数据库
self.database = self.connet[database] #选择需要操作的数据库名称
self.collecttion = self.database[collection] #选择需要操作的集合名称(如果集合名不存在会自动创建)
def insert(self, data, onlyone=True): #输入需要添加的数据(data),onlyone用来控制增加数据是单条还是多条
if onlyone: #控制数据为单条
self.collecttion.insert_one(data) #向集合中增加单条数据
else: #否则为多条数据
self.collecttion.insert_many(data) #向集合中增加多条数据
def find(self, query=None, onlyone=True): #输入查询的条件(query,默认为None指查询全部数据),使用onlyone控制查询的数据是单条还是多条
if onlyone: #默认onlyone为True查询一条数据
result = self.collecttion.find_one(query) #将查询的结构用result变量来接收
return result #返回result
else: #onlyone为False查询多条数据
result = self.collecttion.find(query) #将查询的结构用result变量来接收
return list(result) #返回result,并转换成列表
def updata(self, data, new_data, onlyone=True): #指定需要修改的数据(data),修改后的数据(new_data),onlyone控制修改单条还是多条
if onlyone: #当onlyone为真
self.collecttion.update_one(data, {'$set': new_data}) #修改单条数据,使用'$set'表示指定修改数据否则会使数据库中所有数据被新数据覆盖
else: #当onlyone为假
self.collecttion.insert_many(data, {'$set': new_data}) #修改多条数据,使用'$set'表示指定修改数据否则会使数据库中所有数据被新数据覆盖
def delete(self, data, onlyone=True): #删除数据,data需要删除的数据,使用onlyone控制删除的条数
if onlyone:
self.collecttion.delete_one(data) #删除一条
else:
self.collecttion.delete_many(data) #删除多条
wl = MyMongoDB(‘stu’, ‘wl’) #指定我们需要操作的数据库为stu数据库,需要操作的集合为wl集合
wl.insert([{‘name’: ‘cx’, ‘profession’: ‘bigdata’, ‘age’: 18},{‘name’: ‘fhb’, ‘profession’: ‘bigdata’, ‘age’: 21}], onlyone=False)
#向wl集合中插入两条数据,控制onlyone为False,告知insert函数我们需要插入多条数据
print(wl.find({‘name’: ‘cx’})) #在inset中为我们已经增加了数据,此时查询名字为cx学生信息并打印
wl.updata({‘profession’: ‘bigdata’}, {‘profession’: ‘English’}) #将学生专业为大数据的改成英语专业
print(wl.find(onlyone=False)) #控制onlyone=False,打全部数据
1.连接mongodb
无需权限认证方式
import pymongo
myclient = pymongo.MongoClient(“mongodb://localhost:27017”)
myclient = pymongo.MongoClient(‘localhost’,27017)
print(myclient.list_database_names())
输出:
[‘admin’, ‘config’, ‘local’, ‘test’]
权限认证方式
import pymongo
myclient = pymongo.MongoClient(‘localhost’, 27017)
db = mongo_client.admin
db.authenticate(‘用户名’, ‘密码’)
2.指定数据库和集合
获取数据库
方法一:db = client.test
方法二:db = client[‘test’]
指定集合
方法一:collection = db.stu
方法二:collection = db[‘stu’]
3.插入数据
可以使用insert方法插入数据,但在pymongo中,官方推荐使用 insert_one 完成单个数据的写入,insert_many 完成多条数据的插入。
#增加一条
stu1={‘id’:‘001’,‘name’:‘zhangsan’,‘age’:10}
result = collection.insert_one(stu1)
#增加多条
stu2={‘id’:‘002’,‘name’:‘lisi’,‘age’:15}
stu3={‘id’:‘003’,‘name’:‘wangwu’,‘age’:20}
result = collection.insert_many([stu2,stu3])
4.删除数据
#可以直接使用remove方法删除指定的数据
result = collection.remove({‘name’: ‘zhangsan’})
#使用delete_one()删除一条数据
result = collection.delete_one({“name”:“zhangsan”})
#delete_many()删除多条数据
result = collection.delete_many({“age”:{‘$lt’:20}})
5.修改数据
可以使用update方法修改数据,但在pymongo中,官方推荐使用 update_one 完成单个数据的修改,update_many 完成多条数据的修改。
#update_one,第 2 个参数需要使用KaTeX parse error: Expected 'EOF', got '#' at position 14: 类型操作符作为字典的键名 #̲姓名为zhangsan的记录,…set’: res})
print(result) #返回结果是UpdateResult类型
print(result.matched_count,result.modified_count) #获得匹配的数据条数1、影响的数据条数1
#update_many,所有年龄为15的name修改为xixi
condition = {‘age’: 15}
res = collection.find_one(condition)
res[‘age’] = 30
result = collection.update_many(condition, {‘$set’:{‘name’:‘xixi’}})
print(result) #返回结果是UpdateResult类型
print(result.matched_count,result.modified_count) #获得匹配的数据条数3、影响的数据条数3
6.查询数据
find()查找全部数据
返回所有满足条件的结果,如果条件为空,则返回全部结果,返回结果是一个Cursor游标可迭代对象。
rets = collection.find({“age”:20}),
for ret in rets:
print(ret)
查询结果有多少条数据
count = collection.find().count()
查询结果按年龄升序排序
results = collection.find().sort(‘age’, pymongo.ASCENDING)
print([result[‘age’] for result in results])
find_one()查找一条数据
接收一个字典形式的条件,返回字典形式的整条数据,如果条件为空,则返回第一条。
ret =collection.find_one({‘name’: ‘zhangsan’})