Monthly Archives: January 2016

How to insert ,update, delete into MongoDB NOSQL database with Python

How to insert ,update, delete into  MongoDB NOSQL database with  Python

Watch this 30 minute video to guide you through this process for my database for my trading system

 

How to insert update delete in a MongoDB NOSQL database with Python

 

Source code:

Query

#https://docs.mongodb.org/getting-started/python/query/

from pymongo import MongoClient

client = MongoClient()
# db = client.qln
# cursor = db.qln.find({"positions.shortsymbol": "ibm"})
#
# for document in cursor:
#     print(document)


db = client.qln
collection = db.equity

stocks = collection.find({"shortsymbol": "k"})

print stocks.count()
for stock in stocks:
    print(stock)

Insert

#https://docs.mongodb.org/getting-started/python/insert/
from pymongo import MongoClient

client = MongoClient()
db = client.qln

#db.equity.insert( { "_id": 5, item: "box", qty: 20 } )

# from datetime import datetime
result = db.equity.insert_one(
    { "idx" : 2,
      "shortsymbol" : "k",
      "shortentryts" : 1000,
      "shortentryprice" : 100,
      "shortstoplossper" : 0.08,
      "shortupstop" : 105.1,
      "shortlowstop" : 95.1,
      "shortsofttargperc" : 0.08,
      "shortuptarget" : 105.1,
      "showlowtarget" : 95.1,
      "longsymbol" : "pep",
      "longentryts" : 1000,
      "longentryprice" : 100,
      "longstoplossper" : 0.08,
      "longupstop" : "10.5.1",
      "longlowstop" : 95.1,
      "longsofttarget" : 0.08,
      "longuptarget" : 105.1,
      "longdowntarget" : 95.1,
      "shortexitts" : 1000,
      "shortexitprice" : 95.1,
      "longexitprice" : 105.1,
      "shortqty" : 1000,
      "longqty" : 1000,
      "shortbeta" : 0.95,
      "longbeta" : 1.01
    }

)
print result.inserted_id

#https://docs.mongodb.org/getting-started/python/query/
cursor = db.qln.find()

for document in cursor:
    print(document)


Update

 

#https://docs.mongodb.org/manual/reference/method/db.collection.update/
from pymongo import MongoClient

client = MongoClient()
db = client.qln

result = db.equity.update_one(
    {"shortsymbol": "k"},
    {"$set": {"shortentryprice": 107.5, "shortstoplossper": 1.40}}
)

print result.matched_count
print result.modified_count

Delete

 

#https://docs.mongodb.org/getting-started/python/remove/
from pymongo import MongoClient

client = MongoClient()
db = client.qln

result = db.equity.delete_many({"shortsymbol": "k"})

print result.deleted_count