Reputation: 375
I have a MongoDB query and I want the query to continue after one error and skip that record.
I get the following error:
Error: getMore command failed: { "operationTime" : Timestamp(1547144095, 335), "ok" : 0, "errmsg" : "Failed to parse objectId '' in $convert with no onError value: >Invalid string length for parsing to OID, expected 24 but found 0", "code" : 241, "codeName" : "ConversionFailure", "$clusterTime" : { "clusterTime" : Timestamp(1547144095, 335), "signature" : { "hash" : BinData(0,"aMqO7W+xnEbbUw6UsX/cxr2jxzo="), "keyId" : NumberLong("6626865028530176001") } } }
I don't want to fix the error, I just want to ignore it and want the query to continue. Is there a way to do that?
Upvotes: 0
Views: 3678
Reputation: 65393
Assuming test data like:
db.things.insert([{ myfield: ObjectId()}, { myfield: "Some text"}])
You can avoid passing invalid field values by matching against the expected $type
of the value you are converting:
db.things.aggregate([
{ $match: {
myfield: { $type: "objectId" }
}},
{ $addFields: {
converted: {
$convert: {
input: "$myfield",
to: "objectId",
}
}
}},
])
Alternatively, you could set the onError
value in $convert
to something you can use in your aggregation pipeline (for example, with a $match
or $cond
expression):
db.things.aggregate([
{ $addFields: {
converted: {
$convert: {
input: "$myfield",
to: "objectId",
onError: 0
}
}
}},
{ $match: {
converted: { $ne: 0 }
}}
])
Upvotes: 5