• python操作MongoDB


    import pymongo    # 导入pymongo 包
    
    # 连接MongoDB数据库
    mongo_client = pymongo.MongoClient(host="127.0.0.1",port=27017)
    
    # 选择数据库
    DB = mongo_client["users"]
    
    # 增删改查操作
    
    # 1.查询
    # res = list(DB.school.find())
    # res = DB.school.find_one({"class_name":"S16"},{"_id":0,"student":1})
    # res = DB.school.find_one({"class_name":"S16"})
    # res = DB.school.find_one({"student.name":"Alex"})
    # res = DB.school.find_one({'$or':[{"class_name":"S16"},{"school_name":"OldBoy"}]})
    # res = DB.school.find_one({"userlist":{"$all":[3,4,2]}})
    # print(res)
    # res["_id"] = str(res.get("_id"))
    # import json
    # a = json.dumps(res)
    # print(a)
    
    # 2.增加数据
    # res = DB.school.insert_one({"name":1})
    # print(res,res.inserted_id,type(res.inserted_id))
    # res = DB.school.insert_many([{"name":3},{"name":4},{"name":5}])
    # print(res,res.inserted_ids)
    # 奇葩数据
    # res = DB.oldboy.insert_one({"user_list":[{"hobby":["抽烟","喝酒"]},{"hobby":[{"name":"car","type":"SUV"},{"name":"motor","type":"BMW"}]}]})
    
    
    # 3.修改数据
    # $ 存储 array 符合条件元素的下标索引
    # from bson import ObjectId
    # res = DB.school.update_one({"_id":ObjectId("5c7e280ed0df65358812ccab")},{"$push":{"userlist":888}})
    # res = DB.school.update_one({"userlist":888},{"$set":{"userlist.$":666}})
    # res = DB.school.update_one({"userlist":666},{"$set":{"userlist.0":888}})
    # print(res,res.modified_count)
    """
    {
    "_id" : ObjectId("5c7e3fcbd3620e1130463178"),
    "user_list" : [
    {
    "hobby" : [
    "抽烟",
    "喝酒"
    ]
    },
    {
    "hobby" : [
    {
    "name" : "car",
    "type" : "SUV"
    },
    {
    "name" : "motor",
    "type" : "BMW"
    }
    ]
    }
    ]
    }
    """
    # res = DB.oldboy.find_one({})
    # print(res)
    # for index,item in enumerate(res.get("user_list")):
    # for hobby,hobby_item in enumerate(item.get("hobby")):
    # if type(hobby_item) == dict:
    # if hobby_item.get("name") == "motor":
    # res["user_list"][index]["hobby"][hobby]["type"] = "Suzuki"
    #
    # DB.oldboy.update_one({"_id":res.get("_id")},{"$set":res})
    
    # 4.删除
    # from bson import ObjectId
    # res = DB.oldboy.delete_one({'_id': ObjectId('5c7e3fcbd3620e1130463178')})
    # print(res,dir(res),res.deleted_count)
    
    
    # 选取 跳过 排序
    # res = list(DB.school.find().limit(5).skip(5))
    # print(res,len(res))
    
    # 排序
    # res = list(DB.school.find().limit(5).skip(5).sort("_id",pymongo.ASCENDING))
    # res = list(DB.school.find().limit(5).skip(5).sort("_id",pymongo.DESCENDING))
    # print(res,len(res))
  • 相关阅读:
    JS面向(基于)对象编程--构造方法(函数)
    一个超简单的马里奥游戏
    JavaScript基于对象编程
    JavaScript基础之函数与数组
    Learn CSS
    The first day of HTML
    mysql cmd 无法登录
    datagrid 扩展 页脚 合计功能
    this高级应用
    (xxx.55).toFixed(1) 无法正确进位处理
  • 原文地址:https://www.cnblogs.com/zpf666/p/10485441.html
Copyright © 2020-2023  润新知