יום חמישי, 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)}

אין תגובות:

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