The following code demonstrates the removing of sub document from a document using the pull command .
1: import pymongo2: 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”.
אין תגובות:
הוסף רשומת תגובה