zoukankan      html  css  js  c++  java
  • mongodb的连接与使用

    废话不多说直接上代码

    # coding=utf-8

    from pymongo import MongoClient


    # 实例化和插入
    class TestMongo():
        def __init__(self):
            conn = MongoClient(host='127.0.0.1',port=27017)   # mongo的地址和端口号

            self.collection = conn['test']['t3']   #test是数据库,t3是集合名

        def insert_demo(self):    #插入数据的函数

            ret = self.collection.insert({'name':'python','age':23})
            print(ret)

        def insert_many(self):
            list = [{'name':'test{}'.format(i),'age':i} for i in range(10)]
      ret_list = self.collection.insert_many(list)
      for temp in ret_list.inserted_ids:
        print(temp)


    # 查询和更新
      def find_one(self):
        t = self.collection.find_one({'name':'test10'})
        print(t)

      def find_many(self):
        t = self.collection.find({'name':'test10'})
        for i in t:
          print(i)

        for i in t:
          print(i)  #打印为空,因为当前的游标已在最后一个了,所以无法打印

      def try_update_one(self):
        self.collection.update_one({'name':'test10'},{'$set':{'name':'new_test10'}})

      def try_update_many(self):
        self.collection.update_many({'name':'test10'},{'$set':{'name':'new_test10'}})

      def try_delete_one(self):
        self.collection.delete_one({'name':'test8'})
        print('删除成功')

    if __name__ == '__main__':
      mg = TestMongo()
      # mg.insert_demo()
      # mg.insert_many()
      # mg.find_one()
      # mg.find_many()
      mg.try_delete_one()
      print('-'*100)
      mg.find_many()

    这是我今天闲暇时间写的,本地运行还OK,希望看客们多交流交流^_&

  • 相关阅读:
    PHP安装linux
    nginx 安装
    Redis安装
    linux启动http服务
    收藏的有用的网页
    laravel框架部署后有用命令
    .net 报错access to the path c: empimagefilesmsc_cntr_0.txt is denied
    oracle 触发器
    学习Auxre记录
    mysql数据库索引
  • 原文地址:https://www.cnblogs.com/lax-17xu/p/11727237.html
Copyright © 2011-2022 走看看