yii mongodb 查询以什么开头_爬虫进阶丨MongoDB的用法

e59e1a647e198961280c1aaece011679.png

安装

使用之前,要确保已经安装好了MongoDB并启动了其服务,同时安装好了Python的PyMongo库。

可以参考:https://cuiqingcai.com/5205.html

安装PyMongo

pip install pymongo

连接MongoDB

连接MongoDB时,需要使用过PyMongo库里面的MongoClient。只需要向其传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为port(默认27017)

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

也可以

client = MongoClient('mongodb://localhost:27017/')

指定数据库

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

db = client.test# 也可以写成db = client['test']

指定结合

MongoDB的每个数据库包含许多集合,类似于关系型数据库中的表。

指定一个名称为students的集合

collection = db.students# 也可以写成collection = db['students']

插入数据

示例

- 对students这个集合新建一条学生数据

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

调用collection的insert方法即可插入数据

result = collection.insert(student)print(result)

在MongoDB中,每条数据都有一个_id属性来唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。

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

student1 = {    'id': '20170101',    'name': 'Jordan',    'age': 20,    'gender': 'male'}student2 = {    'id': '20170202',    'name': 'Mike',    'age': 21,    'gender': 'male'}result = collection.insert([student1, student2])print(result)

运行结果

[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

注:PyMongo中,官方不推荐使用insert方法,推荐使用insert_one和insert_many方法。

查询

插入数据后,可以利用find_one或find方法进行查询。

示例

result = collection.find_one({'name': 'Mike'})print(type(result))print(result)

运行结果

<class 'dict'>{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

多条数据的查询,可以使用find方法

示例

- 查找年龄为20的数据

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

运行结果

object at {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'

返回结果是cursor类型,相当于一个生成器。

- 查询年龄大于20的数据

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

$gt意思是大于

比较符号归纳

cf0b26592cb658e9db6c9657d9d6747b.png

- 查询名义以M开头的学生数据

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

功能符号归纳

78fab20b3755d06e6f3a3e4ea2915d70.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值