知识补充1:MongoDB的基本使用方法

NoSQL(Not Only SQL),泛指非关系型数据库。NoSQL是基于键值对的,不需要经过SQL层的解析,数据之间没有耦合性,性能非常高。

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

准备环境:

  • 安装好MongoDB软件,并启动其服务
  • 安装好Python的PyMongo库(pip install pymongo) 

连接MongoDB:

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

import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')

指定数据库(以test为例):

db = client.test

db = client['test']

指定集合(以students为例):

集合即collection,数据库中包含很多集合,类似关系型数据库中的表。

collection = db.students

collection = db['students']

插入单条数据并打印返回的_id属性:

student = {
    'id':'20220202',
    'name':'Jordan',
    'age':20,
    'gender':'male'
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)

插入多条数据并打印返回的_id属性:

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

student2 = {
    'id':'20220222',
    'name':'Mike',
    'age':21,
    'gender':'male'
}
result = collection.insert_many([student1,student2])
print(result)
print(result.inserted_ids)

 ▲返回的是InsertManyResult对象,调用inserted_ids属性可以获取插入数据的_id列表。


查询单条数据:

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

▲结果为字典类型,并且数据多了个_id属性(同插入时获取到的相同)。

根据ObjectId来查询数据(要用到bson库里面的objectid):

from bson.objectid import ObjectId

result = collection.find_one({'_id': ObjectId('61e56ec03af5273b368c95bb')})
print(type(result))
print(result)

▲查询结果同样为字典类型 


查询多条数据:

results = collection.find({'gender': 'male'})
print(type(results))
for result in results:
    print(type(result))
    print(result)

▲查询结果是一个Cursor类型的生成器,可以用for-in语句遍历所有结果,其中每个结果都是字典类型。


条件查询:

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

▲查询结果同样是一个Cursor类型的生成器

比较符号
符号 含义 实例
$lt 小于 {'age':{'$lt':20}}
$gt 大于 {'age':{'$gt':20}}
$lte 小于等于 {'age':{'$lte':20}}
$gte 大于等于 {'age':{'$gte':20}}
$ne 不等于 {'age':{'$ne':20}}
$in 在范围内 {'age':{'$in':[20,30]}}
$nin 不在范围内 {'age':{'$nin':[20,30]}}

results = collection.find({'name':{'$regex':'^M.*'}})
print(type(results))
for result in results:
    print(type(result))
    print(result)

▲利用正则匹配name以M开头的学生数据,查询结果同样是一个Cursor类型的生成器

功能符号
符号 含义 实例 实例含义
$regex 匹配正则表达式 {'name': {'$regex': '^M.*'}} name以M为开头
$exists 属性是否存在 {'name': {'$exists': True}} 存在name属性
$type 类型判断 {'age': {'$type': 'int'}} age的类型为int
$mod 数字模操作 {'age': {'$mod': [5,0]}} age模5余0
$text 文本查询 {'$text': {'$search': 'Mike'}} Mike字符串
$where 高级条件查询 {'where': 'obj.fans_count == obj.follows_count'} 自身粉丝数等于关注数

计数 

count = collection.find().count()
print(count)
# 统计合集中所有数据的条数
count = collection.find({'age':20}).count()
print(count)
# 统计集合中符合条件的数据条数

排序

results = collection.find().sort('age', pymongo.ASCENDING)
print([result['age'] for result in results])
# 依照年龄升序排列,并打印年龄列
# 如果要降序排列,传入pymongo.DESCENDING

偏移

results = collection.find().sort('age', pymongo.ASCENDING).skip(2)
print([result['age'] for result in results])
# 忽略前两个元素,获取第三个元素及后面所有元素
results = collection.find().sort('age', pymongo.ASCENDING).skip(2).limit(3)
print([result['age'] for result in results])
# 获取第三个元素及其后面两个元素,共计3个元素
from bson,objectid import ObjectId
collection.find({'_id':{'$gt':ObjectId('86456555885454dccdd')}})
# 如果数据库中的数据量非常庞大(千万、亿级别),最好不要用大偏移量来查询数据(可能会造成内存溢出),建议用_id属性+比较符号进行查询

更新

condition = {'name':'Mike'}
student = collection.find_one(condition)
student['age']=25
result = collection.update_one(condition,{'$set':student})
print(result)
print(result.matched_count,result.modified_count)

# $set表示其它字段既不会更新,也不会删除,只替换condition字典里面有的字段
# update_one表示只匹配并更新一条数据(存在即更新,不存在即插入)
# result.matched_count表示匹配的数据条数
# result.modified_count表示影响的数据条数

 ▲ update_one方法的返回结果是UpdateResult类型。匹配条数为1条,影响条数也是1条。

condition = {'age':{'$gt':20}}
result = collection.update_one(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)

# $gt表示筛选年龄大于20的student
# $inc表示年龄数据增加1

▲ 匹配条数为1条,影响条数也是1条

condition = {'age':{'$gt':19}}
result = collection.update_many(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)

# update_many表示匹配并更新多条数据

 ▲ 用update_many方法会更新所有符合条件的数据。匹配条数为2条,影响条数也是2条


删除

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

# 用delete_one方法匹配并删除一条数据
# 用deleted_count属性获取删除的数据条数
result = collection.delete_many({'age':{'$lt':30}})
print(result)
print(result.deleted_count)

# 用delete_many方法匹配并删除多条数据

 ▲ delete_many方法返回的是DeleteResult对象;共计删除数据3条


其他操作

PyMongo中提供的其他组合方法:

  • find_one_and_delete(查找后删除)
  • find_one_and_replace(查找后替换)
  • find_one_and_update(查找后更新)

对索引进行的相关操作:

  • create_index
  • create_indexes
  • drop_index

<完>

猜你喜欢

转载自blog.csdn.net/weixin_58695100/article/details/122548098