python访问mongo数据库

 一 建立mongo连接

from pymongo import MongoClient
from bson import ObjectId

host = "host"
username = "username"
password = "password"
database = "database"
port = 27017

# 拼接数据库连接字符串
conn = 'mongodb://{username}:{password}@{host}:{port}/{database}'.format(username=username, password=password, host=host, port=port, database=database)
# 建立连接
dlsdataClient = MongoClient(conn)
# 指定数据库名称
curBase = dlsdataClient.curBase
# 选择集合
collection = curBase.collect

 

二 查询mongo数据库

# 查询 find(query).sort([{"xxx": -1}, {"xxx": 1}]).limit(10),query是查询条件,sort是排序条件,limit是限制返回数量
        for eachone in collection.find({"lastEditor": 2733}, no_cursor_timeout=True).sort([("lastEditTime", -1)]).limit(10):
            idstr = str(eachone["_id"])
            print(idstr)

 

三 更新mongo数据库

# 更新, update(query, update, upsert=false, multi=false, writeConcern=false) query与update是必须,后面3个是可选项
        collection.update({"lastEditor": 2733}, {"$set": {"userCategory": 3}}, False, True)

 

四 pymongo查询sort与limit

for entity in bookvolumnColl.find({"bookId": bookId}).sort([("order", -1)]).limit(1)

 

posted @ 2022-06-10 15:16  江湖凶险  阅读(110)  评论(0编辑  收藏  举报