Update MongoDB collection with python script
<p>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:</p>

<pre><code>from pymongo import MongoClient 

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

<p>I want to be able to update it using scripts that I call (specifically from Team City) like:</p>

<pre><code>python update.py --build-type xyz --status xyz
</code></pre>

<p>How would I go about doing this so that the script would update that specific collection that I want?</p>

<p>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:</p>

<p>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 (<a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">https://docs.python.org/3/library/argparse.html</a>). However I'd suggest to use click (<a href="http://click.pocoo.org/5/" rel="nofollow">http://click.pocoo.org/5/</a>).</p>

<p>Save the following as cli.py</p>

<pre><code>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()
</code></pre>

<p>Then run a command like:</p>

<pre><code>python cli.py --db=test --col=test --build_type=staging --sta
tus=finished
</code></pre>

<p>make sure you have pymongo and click installed:</p>

<pre><code>pip install pymongo click
</code></pre>

python mongodb teamcity pymongo