Python-Mongodb存储

非关系型数据库:
   NoSQL基于键值对的,不需要经过SQL层的解析,性能很高

键值存储数据库,代表有 Redis, Voldemort, Oracle BDB 等。
列存储数据库,代表有 Cassandra, HBase, Riak 等。
文档型数据库,代表有 CouchDB, MongoDB 等。
图形数据库,代表有 Neo4J, InfoGrid, Infinite Graph等。

MongoDB储存:
   基于C++编写的,类似JSON对象。

MongoDB数据库的连接和基本插入:

import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

student = {
    'id': '17031010225',
    'name': 'Zhang',
    'age': 21,
    'gender': 'male'
}

# 插入数据
result = collection.insert(student)
# 返回_id属性来唯一标识
print(result)

同时多条数据的插入:

import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

student1 = {
    'id': '17031010225',
    'name': 'Zhang',
    'age': 21,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}

# 以链表的方式插入数据
result = collection.insert([student1, student2])
# 返回_id属性来唯一标识
print(result)

推荐使用insert_one() 和 insert_many():

import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

student = {
    'id': '17031010225',
    'name': 'Zhang',
    'age': 21,
    'gender': 'male'
}

# 插入数据
result = collection.insert_one(student)
# 返回_id属性来唯一标识
print(result)
print(result.inserted_id)

返回的是insertResult对象,可以调用属性的方法获取其_id

import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

student1 = {
    'id': '17031010225',
    'name': 'Zhang',
    'age': 21,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}

# 以链表的方式插入数据
result = collection.insert_many([student1, student2])
# 返回_id属性来唯一标识
print(result)
print(result.inserted_ids)

同样返回的类型是insertManyResult

查询数据:
   find_one()或find()方法可进行查询

import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 查找命令
result = collection.find_one({'name': 'Mike'})

print(type(result))
print(result)

可以根据Objectld来查询:

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 查找命令
result = collection.find_one({'_id': ObjectId('5d236b5b530a6140405e7281')})

print(result)

多条结果查找:

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 查找命令
results = collection.find({'age': 21})

print(results)
for result in results:
    print(result)

返回的结果是Cursor类型,相当于生成器,可以用于遍历

需要查条件的数据:

result = collection.find({'age': {'$gt': 20}})

$gt 是比较符号,意思是大于

正则表达是匹配:

results = collection.find({'name': {'$regex': '^M.*'}})

计数:
   需要查询多少条数据,可以调用count()方法,如统计所有条数。

count = collection.find().count()
print(count)

统计符合条件的数据:

count = collection.find({'age': 20}).count()
print(count)

排序:
   可以调用sort()方法,对传入排序字段及升降标志即可。

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 排序命令
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])

升序是pymongo.ASCENDING
降序是pymongo.DESCENDING

偏移:
   取某几个位置的元素

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 排序命令
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])

可以用limit()方法来指定要取得结果个数:

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 排序命令
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(3)
print([result['name'] for result in results])

注意:在数据库数量非常庞大得时候。不要使用大得偏移量来查询数据,很可能导致内存溢出。
可以使用以下得查询方式:

from bson.objectid import ObjectId
results = collection.find({'id': {'$gt': ObjectId('5d236b5b530a6140405e7280')}})

启到记录上次查询得_id得作用

更新:
   使用updata()方法进行更新

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 需要更新的某个人
condition = {'name': 'Zhang'}
# 找到这个人
student = collection.find_one(condition)
student['age'] = 99
# 利用update进行更新操作
result = collection.update(condition, student)
print(result)

其中,nModified代表影响的数据条数

另外也可以用KaTeX parse error: Expected '}', got 'EOF' at end of input: …e(condition, {'set’: student})

另外的另外,update()方法官方也不推荐使用。推荐使用update_one()和update_many方法
但是用法更加的严格:

from bson.objectid import ObjectId
import pymongo

# 数据库的连接
# client = MondoClient('mongode://localhost:27017')
client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 需要更新的某个人
condition = {'name': 'Zhang'}
# 找到这个人
student = collection.find_one(condition)
student['age'] = 109
# 利用update进行更新操作
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)

参数需要使用{’$set’: student}的形式
matched_count 获取匹配的条数
modified_count 获取受影响的数据条数

import pymongo

# 数据库的连接

client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 需要更新的某个人
condition = {'age': {'$gt': 20}}
# 执行更新操作
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
# 报错,暂时没找到原因
# print(result.matched_count, result.modified_count)

update_many()方法,将所有符合条件的数据都进行更新:

import pymongo

# 数据库的连接

client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

# 需要更新的某个人,$gt是大于的标记
condition = {'age': {'$gt': 20}}
# 执行更新操作,$inc是加的命令
result = collection.update_many(condition, {'$inc': {'age': 2}})
print(result)

print(result.matched_count, result.modified_count)

删除操作:
   delete_one()和delete_many()

import pymongo

# 数据库的连接

client = pymongo.MongoClient(host='localhost', port=27017)

# 操作School这个数据库
db = client.School
# 指定学生集合
collection = db.students

result = collection.delete_one({'name': 'Mike'})
print(result)
print(result.deleted_count)

result = collection.delete_many({'age': {'$lt':25}})
print(result.deleted_count)

delete_one()删除第一条符合条件的数据
delete_many()删除所有符合条件的数据

扩展:
另外 PyMongo 还提供了一些组合方法,如find_one_and_delete()、find_one_and_replace()、find_one_and_update(),就是查找后删除、替换、更新操作,用法与上述方法基本一致。
另外还可以对索引进行操作,如 create_index()、create_indexes()、drop_index() 等。
详细用法可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html。
另外还有对数据库、集合本身以及其他的一些操作,在这不再一一讲解,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/。

你可能感兴趣的:(爬虫进阶)