pymongo的操作

实例化和插入

from pymongo import MongoClient

class TestMongo:
    def __init__(self):
        client = MongoClient(host="127.0.0.1", port=27017)
        self.collection = client["test"]["t1"]  # 使用方括号的方式选择数据库和集合
    
    def test_insert(self):
        # insert接收字典返回objectId
        ret = self.collection.insert({"name":"test10010","age":33})
        print(ret)
        
    def test_insert_many(self):
        item_list = [{"name":"test100{}".format(i)} for i in range(10)]
        # insert_many接收一个列表,列表中所有需要插入的字典
        t = self.collection.insert_many(item_list)
        for i in t.insert_ids:
            print(i)

插入和更新

    def try_find_one(self):
        # find_one查找并且返回一个结果,接受一个字典形式的条件
        t = self.collection.find_one({"name":"test10005"})
        print(t)
        
    def try_find_many(self):
        # find返回所有满足条件的结果,如果条件为空,则返回数据库的所有
        t = self.collection.find({"name":"test1005"})
        # 结果是一个Cursor游标对象,是一个可迭代对象,可以类似读文件的指针
        for i in t:
            print(i)
        for i in t: # 此时t中没有内容
            print(i)
    
    def try_update_one(self):
        # update_one更新一条数据
        self.collection.update_one({"name":"test10005"},{"name":"new_test10005"})
        
    def try_update_many(self):
        # update_one更新全部数据
        self.collection.update_many({"name":"test1005"},{"$set":{"name":"new_test1005"}})
        
    def try_delete_one(self):
        # delete_one删除一条数据
        self.collection.delete_one({"name":"test10010"})
        
    def try_delete_many(self):
        # delete_many删除所有满足条件的数据
        self.collection.delete_many({"name":"test10010"})
原文地址:https://www.cnblogs.com/colden/p/9865199.html