After a backend error that is now fixed, I have a corrupted database where the category_ids
field is a list of objects with the key “$oid” instead of actual ObjectId objects.
I’m attempting to fix it with this query:
db.products.updateMany(
{
"category_ids": {
$exists: true,
$type: "array",
$elemMatch: {
"$oid": { $exists: true, $type: "string" }
}
}
},
[
{
$set: {
"category_ids": {
$map: {
input: "$category_ids",
as: "item",
in: {
$mergeObjects: [
"$$item",
{
"$oid": {
$cond: [
{
$and: [
{ $ne: ["$$item.$oid", null] },
{ $type: "$$item.$oid", $eq: "string" }
]
},
{ $toObjectId: "$$item.$oid" },
"$$item.$oid"
]
}
}
]
}
}
}
}
}
]
);
But I get a “MongoServerError: unknown operator: $oid” error.
A sample document looks like this:
{
"_id": {
"$oid": "674e47d1aa9a78ec88c7bf07"
},
"name": "Apple iPhone 16 Pro 256GB Dorado",
"listed": true,
"price": 1902,
"currency": "USD",
"pictures": [
"https://www.example.com/asset1",
"https://www.example.com/asset2",
"https://www.example.com/asset3"
],
"group_ids": [],
"category_ids": [
{
"$oid": "674df1c7aa9a78ec88c7be9b"
},
{
"$oid": "674dff94aa9a78ec88c7be9f"
}
],
"custom_fields": {
"description": "blah blah blah"
}
"variants": [],
"variant_selection_mode": "image",
"variant_selection_fields": []
}
Here’s a screenshot comparing how a corrupted document looks like next to a non-corrupted one in MongoDB Compass:
screenshot
(top document is the corrupted one)
Any help would be greatly appreciated.
Thank you, peace
8