mongdb 基础操作模板

# -*- coding: utf-8 -*-
from pymongo import MongoClient


def read_db(db_collect):
    mydict = {
        'url': 'https://www.baidu.com',
        'content': '我是百度'
    }
    mydicts = [{
        'url': 'https://www.baidu.com',
        'content': '我是百度'
    },
        {
            'url': 'https://www.google.com',
            'content': '我是google'
        }]
    condition = {'url': 'https://www.baidu.com'}
    conditions = {'url': {"$regex": "^h"}}  # 通过正则进行匹配所有以h开通的内容
    update_content = {"$set": {"content": "我是卧底"}}
    # 使用 find() 方法来查询指定字段的数据,将要返回的字段对应值设置为 1
    # find()方法可以查询集合中的所有数据
    # 如果我们要对查询结果设置指定条数的记录可以使用 limit() 方法,该方法只接受一个数字参数。
    # sort() 方法第一个参数为要排序的字段,第二个字段指定排序规则,1 为升序,-1 为降序,默认为升序。
    # res_find = db_collect.find({}, {'url': 1, 'content': 1, '_id': 0}).limit(4).sort('url')
    # res_find_one = db_collect.find_one({'url': 'ddpaizhao.com'}, {'content': 1, '_id': 0})
    # db_collect.insert_one(mydict)
    # db_collect.insert_many(mydicts)
    # db_collect.update_one(condition, update_content)
    # db_collect.update_many(conditions, update_content)
    # db_collect.delete_one(conditions)  # 删除一条
    # db_collect.delete_many(conditions)  # 删除多条


if __name__ == '__main__':
    myclient = MongoClient()
    db = myclient['xiaozhan']
    collent = db['liaoyi']
    read_db(collent)

猜你喜欢

转载自blog.csdn.net/haohaomax1/article/details/112689259