# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import json
from pymongo import *

def dump(col, doc):
    print('dumping ' + str(doc))
    for d in col.find(doc):
        print(d)
        #print('Id       : %d' % (d['id']))
        #print('Customer : %s' % (d['customer']))
        #for d1 in d['items']:
        #    print('  %2d %-30s %10s %4d %s' % (d1['no'], d1['name'], d1['price'], d1.get('quantity', 1), d1.get('note', '')))

# open
client = MongoClient('localhost', 27017)
db = client.TestDB
col = db.py_json
# setup
s1 = '{ "id": 1, "customer": "A A", "items": [ { "no": 1, "name": "A good Python book", "price": "19.95" } ] }'
print(s1)
#col.insert_one(json.loads(s1))
s2 = '{ "id": 2, "customer": "B B", "items": [ { "no": 1, "name": "ASUS MB", "price": "249.00" }, { "no": 1, "name": "i5 CPU", "price": "299.00", "note": "handle with care" }, { "no": 1, "name": "4 GB kit", "price": "249.00", "quantity": 4} ] }'
print(s2)
#col.insert_one(json.loads(s2))
# query
d = { } # all
dump(col, d)
d = { 'id': 2 } # where id=2
dump(col, d)
d = { 'customer': 'A A' } # where customer='A A'
dump(col, d)
d = { 'customer': { '$regex': 'A.*' } } # where customer like 'A%'
dump(col, d)
d = { 'items.name': 'i5 CPU' } # where items.name='i5 CPU'
dump(col, d)
d = { 'items.name': { '$regex': '.*Python.*' } } # where items.name like '%Java%'
dump(col, d)
d = { 'id': { '$in': [ 1, 2 ] } } # where id in (1,2)
dump(col, d)
