目录
1、pymongo的安装
pip install pymongo
2、连接数据库
from pymongo import MongoClient
方式一:client = MongoClient()
方式二:client = MongoClient('localhost',27017)
方法三: client = MongoClient('mongodb://localhost:2701')
3、新增数据
from pymongo import MongoClient
from datetime import datetime
class TestMongo(object):
def __init__(self):
self.client = MongoClient('mongodb://localhost:27017/')
# 或者client = MongoClient(host='127.0.0.1',port=27017)
# 也可以指定连接的集合client['admin']['students']
self.db = self.client['admin']
# print(self.client.database_names())
# 添加一条数据
def add_one(self):
post = {'title':'标题','content':'内容','created_at':datetime.now()}
# db.students students 是表名
res = self.db.students.insert_one(post)
return res
# 添加多条数据
def add_more(self):
data_list = [{"name":"test{}".format(i)} for i in range(5)]
res = self.db.students.insert_many(data_list)
return res
mongo = TestMongo()
res = mongo.add_one()
插入的ID
print(res.inserted_id)
4、查询数据
from pymongo import MongoClient
from datetime import datetime
from bson.objectid import ObjectId
class TestMongodb(object):
def __init__(self):
self.client = MongoClient(host='127.0.0.1',port=27017)
db_list = self.client.list_database_names()
self.db = self.client['students']
# 获取1条数据
def get_one(self):
return self.db.students.find_one()
# 查询多条数据
def get_more(self):
return self.db.students.find()
# 查询一条数据
def get_from_id(self,id):
return self.db.students.find_one({'_id':ObjectId(id)})
mongo = TestMongodb()
# 根据记录的ID查询数据
id = '639740bf3910a2c92916bac2'
res2 = mongo.get_from_id(id)
print('res2:',res2)
res3 = mongo.get_more()
for i in res3:
print(i)
# 修改多条数据->所有
def update_all(self):
res = self.db.students.update_many({},{'$set':{'title':'多条修改'}})
print('匹配的数据条数:', res.matched_count)
print('影响的数据条数:', res.modified_count)
# 修改制定条件的多条数据
def update_more(self):
res = self.db.students.update_many({'title':'多条修改'},{'$set': {'title':'修改自定条件的多条数据'}}, True)
print('匹配的数据条数:', res.matched_count)
print('影响的数据条数:', res.modified_count)
6、删除数据
# 删除一条数据
def delete_one(self):
res = self.db.students.delete_one({'title':'修改自定条件的多条数据'})
print('delete_count:',res.deleted_count)
# 删除多条数据
def delete_more(self):
res = self.db.students.delete_many({'title':'标题2'})
print(res.deleted_count)
7、获取数据库
MongoDB的一个实例可以支持多个独立数据库,在使用PyMongo时,可以使用MongoClient实例的属性来进行访问数据库
db = client.pythondb
也可以使用字典形式访问:
db = client['test']
8、获取集合
集合是存储在MongoDB中的一组文档,可以类似于关系数据库中的表。在PyMongo中获取集合的工作方式和获取数据库相同。
collection = db.python_collection
或者
collection = db['python-collection']
9、文档
MongoDB中的数据使用JSON方式来表示文档(并存储),在PyMongo中使用字典来表示文档,如下:以下字典可能用于表示博客文章:
import datetime
from pymongo import MongoClient
client = MongoClient()
post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
10、插入文档
要将文档插入到集合中,可以使用insert_one()
方法:
#!/usr/bin/python3
#coding=utf-8
import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.pythondb
post = {"author": "Maxsu",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
posts = db.posts
post_id = posts.insert_one(post).inserted_id
print ("post id is ", post_id)
插入文档时,如果文档尚未包含“_id
”键,则会自动添加“_id
”。 “_id
”的值在集合中必须是唯一的。 insert_one()
返回一个InsertOneResult
的实例
插入第一个文档后,实际上已经在服务器上创建了帖子(posts
)集合。可以列出数据库中的所有集合:
#!/usr/bin/python3
#coding=utf-8
import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.pythondb
"""
post = {"author": "Maxsu",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
posts = db.posts
post_id = posts.insert_one(post).inserted_id
print ("post id is ", post_id)
"""
cur_collection = db.collection_names(include_system_collections=False)
print("cur_collection is :", cur_collection)
执行上面代码,得到以下结果:
cur_collection is : ['posts']
11、关于Unicode字符串的注释
MongoDB以BSON格式存储数据。BSON字符串是UTF-8编码的,所以PyMongo必须确保它存储的任何字符串只包含有效的UTF-8
数据。 常规字符串(<type'str'>
)被验证并保存不变。 Unicode字符串(<type'unicode'>
)首先被编码为UTF-8
。 我们的示例字符串在Python shell中表示为u'Mike
而不是“Mike”
的原因是PyMongo将每个BSON字符串解码为Python unicode
字符串,而不是常规str。
12、计数统计
如果只想知道有多少文档匹配查询,可以执行count()
方法操作,而不是一个完整的查询。 可以得到一个集合中的所有文档的计数
#!/usr/bin/python3
#coding=utf-8
import datetime
import pprint
from pymongo import MongoClient
client = MongoClient()
db = client.pythondb
posts = db.posts
print("posts count is = ", posts.count())
print("posts's author is Maxsu count is =", posts.find({"author": "Maxsu"}).count())
执行上面代码,得到以下结果:
posts count is = 4
posts's author is Maxsu count is = 2
13、范围查询
MongoDB支持许多不同类型的高级查询。例如,可以执行一个查询,将结果限制在比特定日期更早的帖子,而且还可以按作者对结果进行排序:
#!/usr/bin/python3
#coding=utf-8
import datetime
import pprint
from pymongo import MongoClient
client = MongoClient()
db = client.pythondb
posts = db.posts
d = datetime.datetime(2019, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
pprint.pprint(post)
这里使用特殊的“$lt
”运算符做范围查询,并且还可以调用sort()
来按作者对结果进行排序。
14、索引
添加索引可以帮助加速某些查询,并且还可以添加额外的功能来查询和存储文档。在这个例子中,将演示如何在一个键上创建一个唯一的索引,该索引将拒绝已经存在值的文档插入。首先,我们创建索引:
result = db.profiles.create_index([('user_id', pymongo.ASCENDING)], unique=True)
sorted(list(db.profiles.index_information()))
请注意,现在有两个索引:一个是MongoDB自动创建的在_id
索引,另一个是刚刚创建在user_id
上的索引。
现在来设置一些用户配置文件:
user_profiles = [{'user_id': 211, 'name': 'Luke'},{'user_id': 212, 'name': 'Ziltoid'}]
result = db.profiles.insert_many(user_profiles)
该索引将阻止 user_id
已经在集合中的文档插入:
new_profile = {'user_id': 213, 'name': 'Drew'}
duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
result = db.profiles.insert_one(new_profile) # This is fine.
result = db.profiles.insert_one(duplicate_profile)
## 出现错误提示...
Traceback (most recent call last):
DuplicateKeyError: E11000 duplicate key error index: test_database.profiles.$user_id_1 dup key: { : 212 }
案例:将爬取到的数据保存的mongodb数据库中
1、处理爬取到的数据。需要在管道文件(pipeline.py)中进行处理
在pipeline.py中创建一个新的类
class MongoDBPipelines:
def __init__(self, conn, database):
self.conn = conn
self.database = database
@classmethod
def from_crawler(cls, crawler):
return cls(
conn=crawler.settings.get('MONGODB_CONNECTION_STRING'),
database=crawler.settings.get('MONGODB_DATABASE')
)
# 打开spider
def open_spider(self, spider):
# 创建连接
self.client = pymongo.MongoClient(host=self.conn,port=27017)
# 连接数据库
self.db = self.client[self.database]
def process_item(self, item, spider):
# 集合名称
# name = 'text'
# 默认item类名
name = item.__class__.__name__
self.db[name].insert_one(dict(item))
return item
def close_spider(self, spider):
# 关闭连接
self.client.close()
# 2 管道中配置数据库信息
MONGODB_CONNECTION_STRING = 'localhost'
MONGODB_DATABASE = 'mark'
3、启动管道
ITEM_PIPELINES = {
'my_scrapy.pipelines.MongoDBPipelines': 300,
}