MongoDB 基本操作增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import pymongo 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" : "16" },{ "_id" : 0 , "student" : 1 }) res = DB.school.find_one({ "class_name" : "16" }) res = DB.school.find_one({ "student.name" : "哈哈" }) res = DB.school.find_one({ '$or' :[{ "class_name" : "S16" },{ "school_name" : "清华" }]}) 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)) |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步