简体   繁体   中英

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. I know that to create the collection i can simply use pymongo as follows:

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:

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. The python 3 standard library includes argpase ( https://docs.python.org/3/library/argparse.html ). However I'd suggest to use click ( http://click.pocoo.org/5/ ).

Save the following as 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:

pip install pymongo click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM