Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove attribute from all MongoDB documents using Python and PyMongo

In my MongoDB, a bunch of these documents exist:

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

I want to remove the parent.toremove attribute in every single one.

Using the MongoDB shell, I can accomplish this using:

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

But how do I do this within 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
like image 791
Caroline Avatar asked Apr 07 '14 00:04

Caroline


2 Answers

Put quotes around $unset, name the parameter you're including (multi) and use the correct syntax for true:

mongo.db.collection.update({}, {'$unset': {'parent.toremove':1}}, multi=True)
like image 199
JohnnyHK Avatar answered Nov 14 '22 21:11

JohnnyHK


Just found weird to have to attach an arbitrary value for the field to remove, such as a small number (1), an empty string (''), etc, but it's really mentioned in MongoDB doc, with sample in JavaScript:

$unset

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

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

The specified value in the $unset expression (i.e. "") does not impact the operation.

For Python/PyMongo, I'd like to put a value None:

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

So, for OP's question, it would be:

mongo.db.collection.update({}, {'$unset': {'parent.toremove': None}}, multi=True)
like image 1
themefield Avatar answered Nov 14 '22 21:11

themefield