2

Within a mongodb collection, I have documents that contain lists of embedded documents that look like this (using pymongo with col being an instance of pymongo.collection.Collection):

In [1]: col.find_one({'reqid': 1})
Out[1]: 
{u'_id': ObjectId('4fa3446f1d41c81bba000000'),
 u'reports': [{u'comments': [u'A']},
              {u'comments': [u'B']},
              {u'comments': [u'A', u'B']},
              {u'comments': [u'C']},
              {u'comments': [u'A', u'B', u'C']}],
 ...} # Other fields

I now want with one $set update to reset all comments within a document to the empty list. I have tried the following but it doesn't work:

In [2]: col.update({'reqid': 1}, {'$set': {'reports.comments': []}})
In [3]: col.find_one({'reqid': 1}, {'reports.comments': 1})
Out[3]: 
{u'_id': ObjectId('4fa3446f1d41c81bba000000'),
 u'reports': [{u'comments': [u'A']},
              {u'comments': [u'B']},
              {u'comments': [u'A', u'B']},
              {u'comments': [u'C']},
              {u'comments': [u'A', u'B', u'C']}]}

I looked into the $ positional operator for a possible solution but still can't figure it out. Its pretty straight forward to write the logic in python to do this but would definitely appreciate the elegance of doing this purely with a single pymongo.collection.Collection.update call. Any help would be appreciated.

diliop
  • 9,241
  • 5
  • 28
  • 23
  • Do you want to preserve reports as an array with a bunch of identical entries of {u'comments':[]} members? As many as there were before the update? – Asya Kamsky May 22 '12 at 20:59
  • Yes. I have oversimplified the contents of report above. Each element of reports contains many more fields than just comments. I want to thus preserve all other fields and just set comments to []. – diliop May 22 '12 at 21:40
  • Again, this question has asked at least three times in the past week... – Derick May 23 '12 at 09:25
  • 2
    Wasn't aware that there was a JIRA issue opened for this [here](http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) as linked by a previous answer to a similar [question](http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) – diliop May 23 '12 at 22:59

0 Answers0