. 1 from pymongo Import MongoClient 2 from datetime Import datetime . 3 . 4 . 5 class TestMongo (Object): . 6 . 7 DEF the __init__ (Self): . 8 self.client MongoClient = () # connect to the database . 9 self.db self.client = [ ' Blog ' ] # using the blog database 10 . 11 DEF add_one (Self): 12 is "" " new data " "" 13 is POST = { 14 ' Title ' : ' new title ' , 15 ' Content ' : ' blog content. . . . ' , 16 ' the created_at ' : DateTime.Now (), . 17 ' View ' : 10 18 is } . 19 return self.db.blog.posts.insert_one (POST) # set (table) in a database called blog.posts 20 is 21 is DEF get_one (Self): 22 "" " query a data " "" 23 return self.db.blog.posts. 25 DEF get_more (Self): 26 is "" " Search Data " "" 27 return self.db.blog.posts.find () 28 29 DEF get_from_oid (Self, OID): 30 "" " acquires an ID recorded data "" " 31 is from bson.objectid Import the ObjectId # used to query the data ObjectID 32 return self.db.blog.posts.find_one ({ ' the _id ' : the ObjectId (OID)}) 33 is 34 is DEF Update (Self): 35 "" " modify the data ." "" 36 # modify a data 37 [ REST = self.db.blog.posts.update_one ({ ' view ' : 10}, { ' $ inc is ' : { ' view ' :}}. 1) # $ inc is to increase the view 1, $ set will view provided the specified value 38 is Print (rest.matched_count) # matched_count matching number 39 Print (rest.modified_count) # modified_count successfully modified data quantity 40 # modify a plurality of data 41 is REST = self.db.blog.posts.update_many ({ }, { ' $ inc is ' : { ' View ' : 10}}) #View increases all the 10 42 is Print (rest.matched_count) 43 is Print (rest.modified_count) 44 is 45 DEF Delete (Self): 46 is "" " delete data " "" 47 # delete a data 48 REST = self.db.blog .posts.delete_one ({ ' View ' : 10 }) 49 Print (rest.deleted_count) # DELETED_COUNT data quantity is successfully deleted 50 # deleting a plurality of data 51 is REST = self.db.blog.posts.delete_many ({ ' title ' : ' new title '}) 52 print(rest.deleted_count) 53 54 55 def main(): 56 obj = TestMongo() 57 # rest = obj.add_one() 58 # rest = obj.get_more() 59 # for item in rest: 60 # print(item) 61 # obj.update() 62 # obj.delete() 63 64 65 if __name__ == '__main__': 66 main()