‏הצגת רשומות עם תוויות pymong. הצג את כל הרשומות
‏הצגת רשומות עם תוויות pymong. הצג את כל הרשומות

יום שני, 10 ביוני 2013

Pulling sub document from a document

The following code demonstrates the removing of sub document from a document using the pull command .

  1: import pymongo
  2: from datetime import *
  3: client = pymongo.MongoClient("localhost", 27017)
  4: 
  5: db = client['test-database']
  6: 
  7: userCollection = db['userCollection']
  8: 
  9: userCollection.remove ({"Name":"Uzi"} ,safe=True)
 10: 
 11: new_user = {"Name":"Uzi",
 12:     "Age":90,
 13:     "Childs":["fstChild","scnChild"],
 14:     "dateofbirth" : datetime(1970, 10, 25),
 15:     "email" : "loveme42@hotmail.com",
 16:     "RunningNo":nextNo ,
 17:     "Blog address":"http://zvikastechnologiesblog.blogspot.com",
 18:     "BankAcounts":[{"Name":"Leumi" ,"No":"123"},{"Name":"apoalim" ,"No":"456"}]}
 19: 
 20: userCollection.save (new_user)
 21: 
 22: userCollection.update({"Name":"Uzi"},
 23: {"$pull":{"BankAcounts":{"No":{"$ne":"123"}}}}, safe=True)
 24: 
 25: users = db.userCollection.find({"Name":"Uzi"},limit=1)
 26: 
 27: for user in users:
 28:     print ( type ( user))
 29:     print (  user)

And the result:
{'Age': 90, 'dateofbirth': datetime.datetime(1970, 10, 25, 0, 0), 'Blog address': 'http://zvikastechnologiesblog.blogspot.com', '_id': ObjectId('51b5c0fddef1c125e8218723'), 'RunningNo': 175, 'email': 'loveme42@hotmail.com', 'Name': 'Uzi', 'BankAcounts': [{'Name': 'Leumi', 'No': '123'}], 'Childs': ['fstChild', 'scnChild']}

The Mongo Query removes all the sub documents of docuemnts where the sub docuemnt "No" value is not equal to "123"
Note:There is a deiffrent between 123 and “123”.

יום חמישי, 30 במאי 2013

MongoDB Cont

Deleting documents from collection .
The following code deletes all documents that the property RunningNo value is 9

  1: import pymongo
  2: from datetime import *
  3: client = pymongo.MongoClient("localhost", 27017)
  4: #Create of get the DB  
  5: db = client['test-database']
  6: 
  7: print (db.name)
  8: 
  9: #create user collection
 10: 
 11: userCollection = db['userCollection']
 12: 
 13: for nextNo in range (1,10,2):
 14: 
 15:     new_user = {"Name":"zvika",
 16:                 "Age":42,
 17:                 "Childs":["Lior","Gal","Shahf"],
 18:                 "dateofbirth" : datetime(1970, 10, 25),
 19:                 "email" : "loveme42@hotmail.com",
 20:                 "RunningNo":nextNo ,
 21:                 "Blog address":"http://zvikastechnologiesblog.blogspot.com"}
 22: 
 23:     userCollection.save (new_user)
 24: 
 25: userCollection.remove ({"RunningNo":9} ,safe=True)
 26: 
 27: users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)] ,limit=24)
 28: 
 29: for user in users:
 30:     print ( type ( user))
 31:     print (  user)

 


using sub documents
  1: new_user = {"Name":"zvika",
  2:     "Age":42,
  3:     "Childs":["Lior","Gal","Shahf"],
  4:     "dateofbirth" : datetime(1970, 10, 25),
  5:     "email" : "loveme42@hotmail.com",
  6:     "RunningNo":nextNo ,
  7:     "Blog address":"http://zvikastechnologiesblog.blogspot.com",
  8:     "BankAcounts":[{"Name":"Leumi" ,"No":"123"},{"Name":"apoalim" ,"No":"456"}]}
  9: 
 10: userCollection.save (new_user)
 11: 
 12: users = db.userCollection.find({"BankAcounts.Name":"Leumi"},limit=1)

Note: the code above returns that all  documents that match the query

Setting anew Property
  1: db.userCollection.update({"BankAcounts.Name":"Leumi"},
  2: {"$set":{"NewField":"NewFieldValue"}}, safe=True)

The Result:
{'email': 'loveme42@hotmail.com', 'Name': 'zvika', 'BankAcounts': [{'No': '123', 'Name': 'Leumi'}, {'No': '456', 'Name': 'apoalim'}], 'Childs': ['Lior', 'Gal', 'Shahf'], 'dateofbirth': datetime.datetime(1970, 10, 25, 0, 0), 'Blog address': 'http://zvikastechnologiesblog.blogspot.com', 'RunningNo': 175, 'NewField': 'NewFieldValue', '_id': ObjectId('51a4bcb4def1c124d490d385'), 'Age': 42}


Insert new property to the collection

  1: db.userCollection.update({"BankAcounts.Name":"Leumi"},
  2:     {"$set":{"BankAcounts.$.NewField":"NewFieldValue"}}, safe=True)

note the $ sign is used to represent a collection
The Result:
{'RunningNo': 175, 'BankAcounts': [{'NewField': 'NewFieldValue', 'No': '123', 'Name': 'Leumi'}, {'No': '456', 'Name': 'apoalim'}], '_id': ObjectId('51a4bd67def1c1143c53f8a4'), 'email': 'loveme42@hotmail.com', 'Name': 'zvika', 'Blog address': 'http://zvikastechnologiesblog.blogspot.com', 'Childs': ['Lior', 'Gal', 'Shahf'], 'Age': 42, 'dateofbirth': datetime.datetime(1970, 10, 25, 0, 0)}

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

MongoDB Queries cont

The sample DB for this post :

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

#create user collection

userCollection = db['userCollection']

for nextNo in range (1,10,2):
   new_user = {"Name":"zvika",
                "Age":42,
                "Childs":["Lior","Gal","Shahf"],
                "dateofbirth" : datetime(1970, 10, 25),
                "email" : "loveme42@hotmail.com",
                "RunningNo":nextNo ,
                "Blog address":"http://zvikastechnologiesblog.blogspot.com"}
   userCollection.save (new_user)

Limiting the returned fields from mondo db results :
Return only the age and email fields :

users = db.userCollection.find({"Name":"zvika"},{"Age":1,"email":2})
for user in users:
    print ( type ( user))
    print (  user)
returns:
<class 'dict'>
{'_id': ObjectId('519ddd10def1c122d4074eef'), 'email': 'loveme42@hotmail.com', 'Age': 42}
Add sorting users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)])

Limiting the resutls set
users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)]).limit(1)
Note:the result set limitation in this case is relevant to the sorted field in this case if there is a several documents with the same sorted value than all of them will return.
for an example after running the sample data five times the result of the query will be :
<class 'dict'>
{'email':
'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email':
'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email':
'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email':
'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email':
'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
The same result will be applied to limit 1..5 only if the limit will be greater then 6 the next batch will be returned.

The limit parse could be write although in the following syntex:

users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)] ,limit=24)