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()
    

      

  • 相关阅读:
    [前端插件]Bootstrap Table服务器分页与在线编辑应用总结
    Accord.NET_Naive Bayes Classifier
    Accord.NET入门
    [C++]STL容器Vector的内存释放
    [设计模式]适配器模式与外观模式
    [设计模式]工厂模式
    Linux下spi驱动开发
    Qt移植对USB鼠标键盘、触摸屏的支持
    linux设备模型详解 http://blog.csdn.net/linux_xiaomugua/article/details/6989386
    LGPL协议的理解
  • 原文地址:https://www.cnblogs.com/sike8/p/11230260.html
Copyright © 2011-2022 走看看