Reputation: 41
i wants to delete documents from collection using cursor with pymongo. But i have _id filed as embedded and i have to pass whole _id field for deletion criteria.
{
"_id" : {
"Path" : 0,
"TriggerName" : "KM_Topzones_In App",
"userId" : NumberLong(3408661),
"Date" : "01/09/2017",
"OfferType" : "NOOFFER"
},
"OfferCount" : NumberLong(0),
"OfferName" : "NoOffer",
"desktopTop-normal" : NumberLong(1),
"mrcTop-normal" : NumberLong(1),
"appPostLoginOverlay-normal" : NumberLong(1)
}
Delete query:
>>> cursor=col.find()
>>> slice=cursor[0:5]
>>> for doc in slice:
... print doc['_id']
... result=col.delete_one({"_id": doc['_id']})
... result.deleted_count
...
{u'Date': u'01/09/2017', u'Path': 0, u'OfferType': u'NOOFFER', u'userId': 3408661L, u'TriggerName': u'KM_Topzones_In App'}
0
{u'Date': u'01/09/2017', u'Path': 0, u'OfferType': u'NOOFFER', u'userId': 1587308L, u'TriggerName': u'KM_Topzones_In App'}
0
{u'Date': u'01/09/2017', u'Path': 0, u'OfferType': u'NOOFFER', u'userId': 1049384L, u'TriggerName': u'KM_Topzones_In App'}
0
{u'Date': u'01/09/2017', u'Path': 0, u'OfferType': u'NOOFFER', u'userId': 3029181L, u'TriggerName': u'KM_Topzones_In App'}
0
{u'Date': u'01/09/2017', u'Path': 0, u'OfferType': u'NOOFFER', u'userId': 2884382L, u'TriggerName': u'KM_Topzones_In App'}
0
But that is not deleting anything ,is there a way to do it ??
Please suggest.
Upvotes: 0
Views: 1410
Reputation: 61225
To accomplish this, you need to use the "dot notation" because the field's order matter here.
db.collection.deleteOne({
"_id.Path": 0,
"_id.TriggerName" : "KM_Topzones_In App",
"_id.userId" : NumberLong(3408661),
"_id.Date" : "01/09/2017",
"_id.OfferType" : "NOOFFER"
})
In your case you can build the query filter using a dictionary comprehension like this:
query = {"_id.{key}".format(key=key): value for key, value in doc['_id'].items()}
Then pass the query
to .delete_one()
result = col.delete_one(query)
Upvotes: 1