pymongo - MongoDB: Removing a field from ALL subdocuments in an array field -


i have thousands of documents in format:

{ "_id" : objectid("51e98d196b01c2085c72d731"), "messages" : [     {         "_id" : objectid("520167056b01c20bb9eee987"),         "id" : objectid("520167056b01c20bb9eee987"),      },     {         "_id" : objectid("520167056b01c20bb9eee988"),         "id" : objectid("520167056b01c20bb9eee988"),      },     {         "_id" : objectid("520167056b01c20bb9eee989"),         "id" : objectid("520167056b01c20bb9eee989"),     } ], } 

i need remove duplicate "id" field. have tried:

db.forum_threads.update({}, {$unset: {"messages.$.id": 1}}, {multi: true}); 

this error getting:

cannot apply positional operator without corresponding query field containing array. 

the reason you're getting error because don't have predicate in filter clause. can this:

mongos> db.test.update({"messages.id": {$exists: true}}, {$unset: {"messages.$.id":true}}, {multi:true}) 

and won't error - in fact 1 of documents have id attribute removed. problem positional operator matches first element of array matches predicate, doesn't match elements. bigger issue it's not possible update elements in array in mongodb (https://jira.mongodb.org/browse/server-1243).

you'll either need iterate through each element in array using numerical position ("messages.0.id", "messages.1.id", etc.) or can pull array application, loop through elements , update them, , save array out.

you can see jira ticket issue has been open quite awhile 10gen doesn't seem consider high priority.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -