Python implementation of the MongoDB database additions and deletions to search
Directly on the code
fromPymongoImportmongoclient fromDatetimeImportdatetime fromBson.objectidImportObjectIdclassTestmongo (object):def __init__(self): self.client=mongoclient () self.db= self.client['Blog'] #数据库名称, this requires a new databasedefAdd_one (self):" "New Data" "Post= { 'title':'New New title', 'x': 110, 'content':'Blog content, ...', 'Created_at':d Atetime.now ()}returnSelf.db.blog.test.insert_one (POST) #blog. Test is the collection name in the databasedefGet_one (self):" "querying a single piece of data" " returnSelf.db.blog.find_one ()defGet_more (self):" "querying more than one piece of data" " returnSelf.db.blog.find ()#can add conditions defget_from_oid (self,oid):" "get data based on the ID of the record" "obj=ObjectId (OID)returnSelf.db.blog.find_one ({'_id': obj}) defUpdate (self):" "Modifying Data" " #Modify a piece of dataRest = Self.db.blog.update_one ({'x': 14},{'$inc':{'x': 10}}) #return Rest #modify more than one data returnSelf.db.blog.update_many ({},{'$inc':{'x': 8}}) defDelete (self):" "Delete Data" " #Delete a piece of data #return Self.db.blog.delete_one ({' X ': +}) #Delete more than one piece of data returnSelf.db.blog.delete_many ({'x': 56})defmain (): obj=Testmongo () rest=Obj.add_one ()#rest1 = Obj.get_one () #rest2 = Obj.get_more () Print(rest)" "For item in Rest2:print (item["_id"])" " #rest3 = obj.get_from_oid (' 5a9a638f11e67a4c5cad7331 ') #print (REST3) #rest4 = obj.update () #print (Rest4.matched_count) #print (Rest4.modified_count)Rest5=Obj.delete ()Print(Rest5.deleted_count)if __name__=='__main__': Main ()
Python Operation MongoDB Database