MongoDB-python operation mongodb

installation

pip install pymongo

Connection mongodb

from pymongo Import MongoClient 

my_client = MongoClient ( " 127.0.0.1 " , 27017 ) 

MDB = my_client [ " stutent " ]    # specified library name connection 
Print (MDB) 


# Database (MongoClient (Host = [ '127.0.0.1:27017'] , document_class = dict, tz_aware = False, connect = True), 'stutent') 

# connect = True connection is successful 
# document_class = dict query results are returned in the form of a dictionary

Deletions data change search

Add to

# Add single data 
RES = mdb.user.insert_one ({ " name " : " Boy " })
 Print (res.inserted_id)   # instead of a string 
Print (type (res.inserted_id))   # <class' bson.objectid.ObjectId '> 

# adding a plurality of data 
RES = mdb.stutent.insert_many ([{ " name " : " mustaches " }, { " name " : " flower " }])
 Print (res.inserted_ids)   # [ObjectId('5d2f247ee6390ef6741370a7'), ObjectId('5d2f247ee6390ef6741370a8')]
print(type(res.inserted_ids)) # <class 'list'>

View

Finds the first qualifying data

res = mdb.stutent.find_one({"name":"小黑"})
res = mdb.stutent.find_one({"_id":ObjectId("5d2ed96e38887b85450ed6d8")})

Find all data

mdb.stutent.find = RES ({})    # returns iterable 
Print (List (RES))
 "" " 
for I in RES: 
    Print (I) 
" ""
"" " 
- We query to find all the data 
- if the front page with json data needed to render the page 
- but not the type string _id but ObjectId type, and can not be directly converted into json 
- then we can use the following two ObjectID ways will be converted into json 
"" "

The first way, the efficiency is not high

Import JSON 
res_list = []
 for User in RES:
     # The value of _id converted into a string list 
    User [ " _id " ] = STR (user.get ( " _id " )) 
    res_list.append (User) 
# list serialization 
RET = json.dumps (res_list)
 Print (RET)

The second way, high efficiency

List = RES (mdb.stutent.find ({})) # returns iterable 
Import JSON
 for index, User in the enumerate (RES): 
    RES [index] [ " the _id " ] = STR (user.get ( " _id " )) 
RET = json.dumps (RES)
 Print (RET)

modify

# Modifications meet the first condition of all data 
RES = mdb.stutent.update_one ({ " name " : " flowers " }, { " $ SET " : { " name " : " Small two B " }}) 

# modifications comply all data conditions, it does not add a 
RES = mdb.stutent.update_many ({ " name " : " flowers " }, { " $ SET " : { " name " : " small two B " , "age":80}})
print(res) # {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

Batch operations

S = { " name " : { " $ REGEX " : " Hu " }}    # fuzzy match modifier 
Data = {
     " $ SET " : { " Sex " : " man " , " Hobby " : [ " smoke " , " drink " ]} 
} 
mdb.stutent.update_many (S, Data)

The method of dictionary data in the database can be modified

# Returns the data so qualified first data format and is dict 
RES = mdb.stutent.find_one ({ " name " : " mustaches " })
 # { 'the _id': the ObjectId ( '5d2f246d7fb0bb7a411f350c'), ' name ':' hu ',' sex ':' man ',' hobby ': [' smoke ',' drink ']} 
Print (RES) 

RES [ " Sex " ] = " MALE "    # memory level adaptation dict the data, all of the methods can be used dictionaries 
# update to the database update method 
mdb.stutent.update_one ({ " name " : " mustaches " }, { "$set":{"sex":res.get("sex")}})
# { "_id" : ObjectId("5d2f246d7fb0bb7a411f350c"), "name" : "小胡", "sex" : "male", "hobby" : [ "抽烟", "喝酒" ] }

delete

# Delete only qualified first data 
res = mdb.stutent.delete_one ({ " name " : " Big bared flower " })
 # Returns the number of deleted data 
Print (res.deleted_count) 

# delete all the data in line with the conditions of 
res mdb.stutent.delete_many = ({ " name " : " small two B " })
 Print (res.deleted_count)

Other operations

Import pymongo
 "" " 
DESCENDING descending order 
ASCENDING from small to large 
." "" 
# returns iterable 
# the Sort Sort 
RES = mdb.stutent.find (). the Sort ( " Age " , pymongo.ASCENDING)
 for I in RES:
     Print (I) 

# select 
mdb.stu.find () limit (2. )
 # skip 
mdb.stu.find () skip (2. ) 

# tab 
res = list (mdb.stu.find () .sort ( " Age " , pymongo.ASCENDING) .limit (2) .skip (. 4 ))
 Print (RES)
Import ObjectId BSON from 
# the string into query object ObjectId 
res = mdb.user.find_one ({ "_ id ": ObjectId ( "5d2ed96e38887b85450ed6d8")})

  

Guess you like

Origin www.cnblogs.com/songzhixue/p/11203561.html