美文网首页
mongo-python

mongo-python

作者: jinjin1009 | 来源:发表于2021-06-23 14:35 被阅读0次

    1、用户无权限验证连接mongo

    import pymongo
    
    mongo_conn = None
    try:
        mongo_conn = pymongo.MongoClient(host, port)
        mongo_db = mongo_conn[db_name]
        mongo_coll = mongo_db[coll_name]
        print("conn_mongo: %d" % mongo_coll.count())
    except Exception as ex:
        print("conn mongo error: " + str(ex))
    

    2、用户权限验证登陆连接mongo(1)
    注:有权限校验登陆最好选择这种方式,另一种方式可能会有问题

    import pymongo
    mongo_client = pymongo.MongoClient("%s:%d"%(host, port))
    #其中mechanism 可以替换或者去掉
    mongo_client[db_name].authenticate(user_name, password, db_name, mechanism='MONGODB-CR')
    mongo_db = mongo_client[db_name]
    mongo_coll = mongo_db[coll_name]
    print("conn_mongo -- count: %d" % mongo_coll.count())
    

    3、用户权限验证登陆连接mongo(2)

    uri = "mongodb://{user_name}:{password}@{host}:{port}/{db_name}?authMechanism=MONGODB-CR".format(username=user_name,
                                                                               password=user_pwd,
                                                                               host=host,
                                                                               port=port,
                                                                               db_name=db_name)
        print("conn_mongo -- uri: " + uri)
        mongo_client = pymongo.MongoClient(uri)
        mongo_db = mongo_client[db_name]
        mongo_coll = mongo_db[coll_name]
        print("conn_mongo -- count: %d" % mongo_coll.count())
    

    4、用户权限验证登陆连接mongo集群

    from pymongo import MongoClient
    mongodb_str = "mongodb://%s:%s@" % (MONGODB_USER, MONGODB_PASSWORD)
    if isinstance(MONGODB_URL_LIST, list):
       for mongodb_url in MONGODB_URL_LIST:
           mongodb_str += mongodb_url + ":" + str(MONGODB_PORT) + ","
       mongodb_str = mongodb_str[:-1]
    else:
       mongodb_str = "mongodb://" + MONGODB_URL_LIST + ":" + str(MONGODB_PORT)
    
    def get_mongodb():
       """
       通过pymongo方式连接数据库
       :return: assessDB对象
       """
       while True:
           try:
               mongodb_client = MongoClient(mongodb_str)
               if mongodb_client:
                   logger.info("Connect to mongodb success!")
                   break
               else:
                   logger.error("connect mongodb error")
                   time.sleep(1)
           except Exception as e:
               logger.error("connect mongodb error: " + str(e))
               time.sleep(1)
       return mongodb_client
    mongodb_instance = get_mongodb()[MONGODB_DBNAME]
    

    5、插入数据

    mydict = { "name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com" }
    x = mycol.insert_one(mydict)
    
    mylist = [
      { "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com" },
      { "name": "QQ", "alexa": "101", "url": "https://www.qq.com" },
      { "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" },
      { "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com" },
      { "name": "Github", "alexa": "109", "url": "https://www.github.com" }
    ]
    x = mycol.insert_many(mylist)
    

    6、查询数据
    按照时间倒排,固定查询5条

    results = mongo_coll.find().sort("time", -1).limit(5)
    

    7、查询数据
    只展示某个字段,其中常用的id字段不展示,展示field字段

    results = mongo_coll.find({},{"_id": 0, field: 1})
    

    详情参考https://juejin.cn/post/6844903597465927694#heading-5

    相关文章

      网友评论

          本文标题:mongo-python

          本文链接:https://www.haomeiwen.com/subject/ndsbyltx.html