יום שישי, 24 במאי 2013

MongoDB simple sample

If the mongod.bat failed to start due to wrong DB path Start the mongodb: mongod -dbpath c:\data where c:\data is an valid and exist path.
I found that using  pymongo driver in order to interact with mongodb is very powerful tool

Simple sample: import pymongo
from datetime import *
client = pymongo.MongoClient("localhost", 27017)
#Create of get the DB 
db = client['test-database']
print (db.name)

#create user collection
userCollection = db['userCollection']

new_user = {"Name":"zvika",
            "Age":42,
            "Childs":["Lior","Gal","Shahf"],
            "dateofbirth" : datetime(1970, 10, 25),
            "email" : "loveme42@hotmail.com"}

userCollection.save (new_user)

users = db.userCollection.find({"Name":"zvika"})
for user in users:
    print ( type ( user))
    print (user.get("Childs"))
The sample  creates  a connection to the local mongo db server .
Gets a reference to a test-client DB  if not exists create it.
Get a reference to the user-collection  if not exits create it.
Add a simple documents to the collection .
Query for the document with the criteria name = zvika
Note the return value is  a list  of dictionaries containing the  query returned documents.

אין תגובות:

הוסף רשומת תגובה