用python脚本更新MongoDB集合

2024-04-20 13:09:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够创建一个新的空集合,该集合将在调用python脚本时随时更新。我知道要创建集合,我可以简单地使用pymongo,如下所示:

from pymongo import MongoClient 

db = MongoClient('my.ip.add.ress', 27017)['xxxx'] #connect to client
db.createCollection("colName")                    #create empty collection

我希望能够使用我称之为(特别是来自Team City)的脚本来更新它,例如:

^{pr2}$

我该怎么做才能让脚本更新我想要的特定集合?在


Tags: tofromimportip脚本clientadddb
1条回答
网友
1楼 · 发布于 2024-04-20 13:09:04

我想你知道你喜欢修改哪个集合。如果这样做,则只需将集合作为另一个参数添加到命令中:

之后,可以使用系统argv或者专门用来解析命令行参数的库。python3标准库包括argpase(https://docs.python.org/3/library/argparse.html)。但是我建议使用click(http://click.pocoo.org/5/)。在

将以下内容另存为cli.py文件在

import click
from pymongo import MongoClient


MONGOHOST = 'localhost'
MONGOPORT = 27017


@click.command()
@click.option(' db', help='Database', required=True)
@click.option(' col', help='Collection', required=True)
@click.option(' build_type', help='Build Type', required=True)
@click.option(' status', help='Status', required=True)
def update(db, col, build_type, status):
    mongocol = MongoClient(MONGOHOST, MONGOPORT)[db][col]
    mongocol.insert_one({'build_type': build_type, 'status': status})
    # You could also do: mongocol.find_and_modify() or whatever...

if __name__ == '__main__':
    update()

然后运行如下命令:

^{pr2}$

确保已安装pymongo并单击“已安装”:

pip install pymongo click

相关问题 更多 >