使用 python 脚本更新 MongoDB 集合

Update MongoDB collection with python script

我希望能够创建一个新的空集合,该集合将在调用 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)对其进行更新,例如:

python update.py --build-type xyz --status xyz

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

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

之后,您可以使用 sys.argv 或专门为解析命令行参数而编写的库来获取命令行参数。 python 3 标准库包括 argpase (https://docs.python.org/3/library/argparse.html). However I'd suggest to use 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()

然后 运行 命令如下:

python cli.py --db=test --col=test --build_type=staging --sta
tus=finished

确保你有 pymongo 并点击安装:

pip install pymongo click