zoukankan      html  css  js  c++  java
  • MogoDB4

    from pymongo import MongoClient

    #创建链接对象
    conn=MongoClient('localhost',27017)

    #创建集合对象和数据库对象
    db=conn.stu

    my_set=db.class1

    索引

    index=my_set.ensure_index('name')

    创建复合索引

    index=my_set.ensure_index([('name',1),('Age',1)])

    创建唯一索引

    index=my_set.ensure_index('name',unique=True)

    创建稀疏索引

    index=my_set.ensure_index('name',sparse=True)

    查看集合中的索引

    list_indexes

    for i in my_set.list_indexes():
        print(i)

    删除索引

    drop_index():删除某一个索引

    my_set.drop_index('name_1')---------name_1是索引的名称

    drop_indexes():删除所有索引

    my_set.drop_indexes()

    聚合操作

    aggregate([])

    参数:与mongoshell中聚合参数写法一致

    返回值:迭代器,同find的返回值

    l=[{'$group':{'_id':'$gender','count':{'$sum':1}}},
    {'$match':{'count':{'$gt':1}}}
    ]
    cursor=my_set.aggregate(l)
    for i in cursor:
       print(i)

    Mongo大文件存储

    from pymongo import MongoClient
    
    import bson.binary
    
    conn=MongoClient('localhost',27017)
    
    db=conn.file
    
    my_set=db.img
    #存储
    f=open('picture.jpg','rb')
    #将读取的二进制流,变为bson格式二进制的字串
    content=bson.binary.Binary(f.read())
    
    my_set.insert({'filename':'picture.jpg','data':content})
    
    conn.close()
    

      

    > show dbs
    admin    0.000GB
    config   0.000GB
    file     0.005GB
    grid_db  0.005GB
    local    0.000GB
    stu      0.000GB
    > 
    
    > show tables
    img
    

      

    大文件的提取

    from pymongo import MongoClient
    
    import bson.binary
    
    conn=MongoClient('localhost',27017)
    
    db=conn.file
    
    my_set=db.img
    data=my_set.find_one({'filename':'picture.jpg'})
    with open(data['filename'],'wb') as f:
    	f.write(data['data'])
    conn.close()
    

      

  • 相关阅读:
    常用方法 反射常见方法
    常用方法 字符串是否是中文
    常用方法 读取 Excel的单位格 为 日期格式 的数据
    常用方法 保证数据长度相同
    常用方法 简单缓存
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P3905 道路重建
    关于宏定义
    P3512 [POI2010]PIL-Pilots
    P2398 GCD SUM
  • 原文地址:https://www.cnblogs.com/sike8/p/11230260.html
Copyright © 2011-2022 走看看