【问题标题】:How do I discard a record that throws an error?如何丢弃引发错误的记录?
【发布时间】:2019-06-05 16:20:48
【问题描述】:

我有一个 MongoDB 查询,我希望查询在出现一个错误后继续并跳过该记录。

我收到以下错误:

错误:getMore 命令失败:{ "operationTime" : 时间戳(1547144095, 335), “好”:0, "errmsg" : "在 $convert 中解析 objectId '' 失败,没有 onError 值:>解析为 OID 的字符串长度无效,预期为 24,但发现为 0", “代码”:241, "codeName" : "转换失败", “$clusterTime”:{ "clusterTime" : 时间戳(1547144095, 335), “签名” : { “哈希”:BinData(0,"aMqO7W+xnEbbUw6UsX/cxr2jxzo="), "keyId" : NumberLong("6626865028530176001") } } }

我不想修复错误,我只想忽略它并希望继续查询。有没有办法做到这一点?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    假设测试数据如下:

     db.things.insert([{ myfield: ObjectId()}, { myfield:  "Some text"}])
    

    您可以通过匹配您要转换的值的预期$type 来避免传递无效的字段值:

    db.things.aggregate([
        { $match: {
            myfield: { $type: "objectId" }
        }},
        { $addFields: {
            converted: {
                $convert: { 
                    input: "$myfield",
                    to: "objectId",
                }
            }
        }},
    ])
    

    或者,您可以将$convert 中的onError 值设置为您可以在聚合管道中使用的值(例如,使用$match$cond 表达式):

    db.things.aggregate([
        { $addFields: {
            converted: {
                $convert: { 
                    input: "$myfield",
                    to: "objectId",
                    onError: 0
                }
            }
        }},
        { $match: {
            converted: { $ne: 0 }
        }}
    ])
    

    【讨论】:

    • 是的!这就是发生的事情。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多