2016-09-28 102 views
0

我希望能够创建一个新的空集合,在任何时候调用python脚本时都会进行更新。我知道,创建集合,我可以简单地使用pymongo如下:使用python脚本更新MongoDB集合

from pymongo import MongoClient 

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

我希望能够用我称之为(特别是从团队市)脚本喜欢它更新:

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

我该如何去做,以便脚本能更新我想要的特定集合?

回答

0

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

之后,你可以通过使用sys.argv或专门编写用于解析命令行参数的库来获取命令行参数。 python 3标准库包含argpase(https://docs.python.org/3/library/argparse.html)。不过,我建议使用点击(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 
+0

感谢的人。得到它的工作。 – user3504250