数据库学习提升模版

《七天爬虫进阶系列》 - 03 数据存储之 MongoDB

2020-02-23  本文已影响0人  聂云⻜

MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。

在开始之前,请确保已经安装好了MongoDB并启动了其服务,并且安装好了Python的PyMongo库。

  1. 创建MongoDB链接对象
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)

连接MongoDB时,我们需要使用PyMongo库里面的MongoClient。一般来说,传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为端口port(如果不给它传递参数,默认是27017)

client = MongoClient('mongodb://localhost:27017/')
  1. 指定数据集

MongoDB中可以建立多个数据库,接下来我们需要指定操作哪个数据库。

db = client.test
  1. 指定集合

MongoDB的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。

collection = db.students
  1. 插入数据
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
# result = collection.insert(student)
result = collection.insert_one(student)
print(result)

在MongoDB中,每条数据其实都有一个_id属性来唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。insert()方法会在执行后返回_id值。

插入多条数据,只需要以列表形式传递即可

student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

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

# result = collection.insert([student1, student2])
result = collection.insert_many([student1, student2])
print(result)
  1. 查询数据库
result = collection.find_one({'name': 'Mike'})
print(type(result))
print(result)
from bson.objectid import ObjectId

result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)

查询多条数据

results = collection.find({'age': {'$gt': 20}})
print(results)
for result in results:
    print(result)

这里查询的条件键值已经不是单纯的数字了,而是一个字典,其键名为比较符号$gt,意思是大于,键值为20。这里将比较符号归纳为下表。

上一篇 下一篇

猜你喜欢

热点阅读