[英]Update MongoDB collection with python script
I want to be able to create a new empty collection that will update any time a python script is called. 我希望能够创建一个新的空集合,该集合将在每次调用python脚本时更新。 I know that to create the collection i can simply use pymongo as follows: 我知道要创建集合,我可以简单地使用pymongo,如下所示:
from pymongo import MongoClient
db = MongoClient('my.ip.add.ress', 27017)['xxxx'] #connect to client
db.createCollection("colName") #create empty collection
I want to be able to update it using scripts that I call (specifically from Team City) like: 我希望能够使用我调用的脚本(特别是来自Team City)来更新它,例如:
python update.py --build-type xyz --status xyz
How would I go about doing this so that the script would update that specific collection that I want? 我将如何执行此操作,以便脚本将更新所需的特定集合?
I suppose you know which collection you like to modify. 我想您知道您要修改哪个集合。 If you do, you can just add the collection as another argument to your command: 如果这样做,您可以将集合作为另一个参数添加到命令中:
After that you can fetch the command line arguments by using sys.argv or a library specifically written to parse command line arguments. 之后,您可以使用sys.argv或专门为解析命令行参数而编写的库来获取命令行参数。 The python 3 standard library includes argpase ( https://docs.python.org/3/library/argparse.html ). python 3标准库包含argpase( https://docs.python.org/3/library/argparse.html )。 However I'd suggest to use click ( http://click.pocoo.org/5/ ). 不过,我建议您使用click( http://click.pocoo.org/5/ )。
Save the following as cli.py 将以下内容另存为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()
Then run a command like: 然后运行以下命令:
python cli.py --db=test --col=test --build_type=staging --sta
tus=finished
make sure you have pymongo and click installed: 确保您拥有pymongo并单击安装:
pip install pymongo click
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.