yanivk1984
6/21/2019 - 4:48 PM

pymongo python

# Import the python libraries
from pymongo import MongoClient

# Choose the appropriate client
client = MongoClient()

# Connect to the customer db 
db=client.customer

# in case that the database has the '-' in between. we cam perform the following:
db = client['test-database']

# connect to a collection - equivalent to a table in sql database
employee = db.employee
employee_details = {
    'Name': 'Raj Kumar',
    'Address': 'Sears Streer, NZ',
    'Age': '42'
}

# Use the insert method in order to insert a json to the employee collection
result = employee.insert_one(employee_details)

# Query for the inserted document.
Queryresult = employee.find_one({'Age': '42'})
pprint(Queryresult)

# updating value by a specific condition
# in here we are updating one docuemnt that has a key of 42 to a new document
db.employee.update_one(
        {"Age":'42'},
        {
        "$set": {
            "Name":"Srinidhi",
            "Age":'35',
            "Address":"New Omsk, WC"
        }
        }
    )

# deleting a document
# in here we are deleting one document that has a specific property.
db.employee.delete_one({"Age":'35'})


# in order to see all the collection names / table names
db.list_collection_names()

# insert bulks, insert complete arrays using insert_many
>>> new_posts = [{"author": "Mike",
...               "text": "Another post!",
...               "tags": ["bulk", "insert"],
...               "date": datetime.datetime(2009, 11, 12, 11, 14)},
...              {"author": "Eliot",
...               "title": "MongoDB is fun",
...               "text": "and pretty easy too!",
...               "date": datetime.datetime(2009, 11, 10, 10, 45)}]
>>> result = posts.insert_many(new_posts)

#Querying for more than one document (document is like a line in a table, its an object in json)
for post in posts.find():
...   pprint.pprint(post)

# we can also filter in the loop
>>> for post in posts.find({"author": "Mike"}):
...   pprint.pprint(post)

# getting the total number of documents 
posts.count_documents({})

#getting the amount of query results
posts.count_documents({"author": "Mike"})


# MongoDB supports many different types of advanced queries. As an example, lets perform a query where we limit results to posts older than a certain date, but also sort the results by author:
d = datetime.datetime(2009, 11, 12, 12)
>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):
...   pprint.pprint(post)
# Here we use the special "$lt" operator to do a range query, and also call sort() to sort the results by author.