zoukankan      html  css  js  c++  java
  • MongoDB代码——Python篇

    需要安装的库:pymongo

    一、添加文档

    from pymongo import MongoClient
    # 连接服务器
    conn = MongoClient("localhost", 27017)
    # 连接数据库,mydb是数据库名
    db = conn.mydb
    # 获取集合,student是集合名
    collection = db.student
    # 添加文档 # collection.insert({"name":"abc", "age":19, "gender":1,"address":"北京", "isDelete":0}) # 添加多个文档 collection.insert([{"name":"abc1", "age":19, "gender":1,"address":"北京", "isDelete":0},{"name":"abc2", "age":19, "gender":1,"address":"北京", "isDelete":0}])
    # 断开连接 conn.close()

    二、查询文档

    import pymongo
    #用于ID查询
    from bson.objectid import ObjectId
    
    # 查询部分文档
    res = collection.find({"age":{"$gt":18}})
    for row in res:
        print(row)
        print(type(row))
    
    # 查询所有文档
    res = collection.find()
    for row in res:
        print(row)
        print(type(row))
    
    # 统计查询
    res = collection.find({"age":{"$gt":18}}).count()
    print(res)
    
    # 根据id查询
    res = collection.find({"_id":ObjectId("5995084b019723fe2a0d8d14")})
    print(res[0])
    
    # 排序,默认升序
    # res = collection.find().sort("age")
    # 降序需要 import pymongo
    res = collection.find().sort("age", pymongo.DESCENDING)
    for row in res:
        print(row)
    
    # 分页查询
    res = collection.find().skip(3).limit(5)
    for row in res:
        print(row)

    三、更新文档

    collection.update({"name":"lilei"},{"$set":{"age":25}})

    四、删除文档

    # 按条件删除
    collection.remove({"name":"lilei"})
    # 全部删除
    collection.remove()

    完成

  • 相关阅读:
    create-react-app 修改 webpack output.publicPath
    洛谷 P1282 多米诺骨牌 (01背包)
    UVa 1627
    UVa 1626
    UVa 11584
    UVa 11400
    UVa 116
    UVa 1347 Tour (dp)
    树形背包小结
    数据流图题目一
  • 原文地址:https://www.cnblogs.com/Rain2017/p/10313924.html
Copyright © 2011-2022 走看看