Remove attribute from all MongoDB documents using Python and PyMongo

In my MongoDB there is a bunch of these documents:

{ "_id" : ObjectId("5341eaae6e59875a9c80fa68"), "parent" : { "tokeep" : 0, "toremove" : 0 } } 

I want to remove the parent.toremove attribute in each of them.

Using the MongoDB shell, I can accomplish this using:

 db.collection.update({},{$unset: {'parent.toremove':1}},false,true) 

But how to do it in Python?

 app = Flask(__name__) mongo = PyMongo(app) mongo.db.collection.update({},{$unset: {'parent.toremove':1}},false,true) 

returns the following error:

  File "myprogram.py", line 46 mongo.db.collection.update({},{$unset: {'parent.toremove':1}},false,true) ^ SyntaxError: invalid syntax 
+10
python mongodb pymongo
source share
2 answers

Put quotation marks around $unset , name the parameter you include ( multi ), and use the correct syntax for true:

 mongo.db.collection.update({}, {'$unset': {'parent.toremove':1}}, multi=True) 
+20
source share

It was just strange to add an arbitrary value for a field that needs to be removed, for example, a small number (1), an empty string (''), etc., but this was really mentioned in the MongoDB documentation, with an example in JavaScript:

$ unset

The $ unset operator deletes a specific field. Consider the following syntax:

{$ unset: {field1: "", ...}}

The specified value in the $ unset expression (i.e., "") is not affected by the operation.

For Python / PyMongo, I would like to specify a value of None :

 {'$unset': {'field1': None}} 

So, for the OP question, this will be:

 mongo.db.collection.update({}, {'$unset': {'parent.toremove': None}}, multi=True) 
0
source share

All Articles