• MongoDB数据库及其Python用法


    一 、命令行模式

    mongo       #  进入mongodb命令行模式
    show dbs
    use taobao      # 进入该数据库,如不存在则创建之
    show tables
    
    # 条件操作符
    (>) 大于 - $gt   # greater than
    (<) 小于 - $lt   # less than
    (>=) 大于等于 - $gte  # e equal
    (<= ) 小于等于 - $lte
    # 查询 db.product.
    find().pretty().limit(10).skip(12).sort({'price':1}) # pretty()以易读的方式,limit()限制个数,skip()跳过前12个记录查找,sort()排序,1为升序,-1为降序 db.product.findOne() # 查找一条记录,此时不能带pretty() db.col.find({"by":"菜鸟教程", "title":"MongoDB 教程"}).pretty() # and db.col.find({$or:[{"by":"菜鸟教程"},{"title": "MongoDB 教程"}]}).pretty() # or db.col.find({"likes": {$gt:50}, $or: [{"by": "菜鸟教程"},{"title": "MongoDB 教程"}]}).pretty() # and 与 or一起用 # 插入 db.person.insert({'name':'老王'}) 插入数据,如果表person不存在,则会自动创建它再插入。 db.person.drop() # 删除表,如果数据库中只有这一张表,那么数据库也会删除。 # 更新 db.person.update({'name':'kris'},{$set:{'name':'chau'}}) db.person.update({'contry':'china'},{$set:{'class':'five','name':'Low'}},{upsert:true}) db.collection.update( <query>, # 查找条件 <update>, # 更新内容 { # 此括号内可选 upsert: <boolean>, # 如果更新内容在记录中不存在,是否插入,默认False multi: <boolean>, # 默认false,只更新找到的第一条记录,否则更新所有找到的记录 writeConcern: <document> # error 级别 } ) # 删除 use datatry db.dropDatabase() # 进入后再执行可删除数据库。 db.person.remove({'name':'chau'}) db.collection.remove( <query>, # 条件 { justOne: <boolean>, # 如果为true或1,则只删除第一条 writeConcern: <document> # 抛出异常级别 } ) # 聚合管道 db.product.aggregate( [ {$match:{m_id:10001,mark_time:{$gt:new Date(2017,8,0)}}}, {$group: { _id: {$dayOfMonth:'$mark_time'}, pv: {$sum: 1} } }, {$sort: {"_id": 1}} ])

    二、Python用法

    import pymongo
    # 连接数据库
    client = pymongo.MongoClient('localhost',27017)
    db = client['taobao']
    # 查找
    datas = db['product'].find_one()
    datas = db['product'].find({'name':'kris'}).skip(2).limit(n) 
    # 插入
    db['person'].insert({'hello':'you are beautiful'})    # insert不用遍历,效率高
    person.insert_many(new_posts)  #  插入多条
    db['person'].save({'hello':'you are beautiful'})      # save需要遍历列表,一个个插入
    # 更新
    # update,$set:更新操作,multi=True:是否对查询到的全部数据进行操作,upsert=True:如果找不到查询的结果是否插入一条数据
    db.user.update_one({"age":"2"},{"$set":{"name":"qian","age":2}})
    db.user.update({"name":"sun"},{"$set":{"name":"qian"}},upsert=True)
    # *update_one也是只能对一条数据进行操作,$set是update操作的$操作符,也可以用$inc或$push,前两个操作速度差不多,$push操作速度较慢。
    person.update({'name':'kris'}, {'$set':{'class':4}})
    # 删除
    person.remove({'$or':[{'author':'Mike'},{'author':'Eliot'}]})

    或者写成类方法调用

    class MyMongoDB(object):
        def __init__(self):
            try:
             self.conn = pymongo.MongoClient(settings["ip"], settings["port"])
            except Exception as e:
             print(e)
            self.db = self.conn[settings["db_name"]]
            self.table = self.db[settings["table_name"]]
    
        def insert(self,dic):
            print("insert...")
            self.table.insert(dic)
    
        def update(self,dic,newdic):
            print("update...")
            self.table.update(dic,newdic)
    
        def delete(self,dic):
            print("delete...")
            self.table.remove(dic)
    
        def dbfind(self,*dic):
            print("find...")
            data = self.table.find(*dic)
            return data
  • 相关阅读:
    Django 之 ORM
    python 变量问题 提问有大佬知道吗?
    celery 使用详解
    ubuntu 网络图标消失问题解决
    django + uwsgi 部署上线
    Python pip常用源地址
    ConfigParser 模块 使用
    Mysql 远程登录问题解决
    商城项目 从设想到实现
    硬盘上有打开的锁和感叹号标志如何解决(win10系统)
  • 原文地址:https://www.cnblogs.com/zongfa/p/8029599.html
Copyright © 2020-2023  润新知