【爬虫】数据的存储[MongoDB]

'''
Author: zh (RickSchanze) (帝皇の惊)
Date: 2022-04-28 22:49:52
Description: MongoDB的使用
LastEditTime: 2022-05-02 22:39:00
'''

import pymongo

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

# 指定数据库
db = client.test  # db = client['test']

# 指定集合
collection = db.students  # collection = db['students']

# 插入数据: 单条数据传字典,使用insert_one;多条传字典组成的列表,使用insert_many
student = {
    "id": 20170101,
    "name": "Jordan",
    "age": 20,
    "gender": "male"
}

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

students = [
    {
        "id": 1,
        "name": "Mike",
        "age": 18,
        "gender": "famale"
    },
    {
        "id":2,
        "name":"zhouhao",
        "age":19,
        "gender":"male"
    }
]
result = collection.insert_many(students)
print(result)

# 查询 find/find_one
result = collection.find_one({'name':'Mike'})
print(type(result))
print(result)

# 根据obejctID来查询
from bson.objectid import ObjectId
result = collection.find_one({'_id':ObjectId('626b43bfd68f766732fac49d')})
print(result)

# 多条数据
results = collection.find({'age':20})
print(results)
for result in results:
    print(result)

# 查询小于20的数据
results = collection.find({'age':{'$lte':20}})
print(results)
for result in results:
    print(result)

# 正则匹配查询
results = collection.find({'name':{'$regex':'^M.*'}})
print(results)
for result in results:
    print(result)

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

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

'''
    偏移
'''
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# 限制个数
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(1)
print([result['name'] for result in results])

'''
    更新
'''
condition = {'name':'Json'}
student = collection.find_one(condition)
student['name'] = 'Jordan'
print(student)
result = collection.update_one(condition, {'$set':student})
print(result)
print(result.matched_count, result.modified_count)

'''
    删除使用delete_one与delete_many
'''
result = collection.remove({'name':'zhouhao'})
print(result)

  

posted @ 2022-05-02 22:40  帝皇の惊  阅读(20)  评论(0)    收藏  举报