Due to a bug in my PHP script, I have created multiple erroneous entries in my MongoDB. Specifically, I was using $addToSet and $each and under certain circumstances, the MongoDB object gets updated wrongly as below:
array (
'_id' => new MongoId("4fa4f815a6a54cedde000000"),
'poster' => 'alex@randommail.com',
'image' =>
array (
'0' => 'image1.jpg',
'1' => 'image2.jpg',
'2' => 'image3.png',
'3' =>
array (
'$each' => NULL,
),
),
You can see that “image.3” is different from the other array entries, and that was the incorrect entry. I have fixed the related in my PHP script, however I am having difficulties tracking down all the affected entries in MongoDB to remove such entries.
Is there any way in MongoDB to check if any of the image array entry contains another array instead of string? Since the index of containing the sub-array is a variable, it would not be possible to perform a $type check on image.3 for every entry.
Could use any suggestion. Thanks!
Since this was an error in your PHP, I suppose, now you want to upgrade all erroneous documents.
If so, you could just find all documents where array item is an array itself.
Now let’s fix this. To remove such entries without fetching them to PHP I offer this simple two-step operation.
First, find all documents with arrays and unset those arrays. This will leave nulls in place of them. Note, it will only match and update first array in the document. If there are several, you want to repeat the operation
Remove nulls.