【问题标题】:Mongodb fails validation even if no document was matched即使没有匹配的文档,Mongodb 也无法验证
【发布时间】:2019-11-22 18:17:27
【问题描述】:

使用 mongo shell,我可以找到一个文档。

但是,在进行无操作更新时,没有匹配的文档,而且由于某种原因,某个地方的文档验证失败。

这怎么可能?会发生什么?我错过了什么吗?

> db.synchronousEvents.count({_id: ObjectId('5dd82343a23aa2b0d5a147cf')})
1
> db.synchronousEvents.update({_id: ObjectId('5dd82343a23aa2b0d5a147cf')}, {})
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})

【问题讨论】:

    标签: mongodb nosql mongo-shell mongodb-update


    【解决方案1】:

    nMatched 为 0,因为这是任何抛出的写入的预​​期行为。

    查看测试:

    //
    // Update with error
    coll.remove({});
    coll.insert({foo: "bar"});
    printjson(result = coll.update({foo: "bar"}, {$invalid: "expr"}));
    assert.eq(result.nUpserted, 0);
    assert.eq(result.nMatched, 0);
    if (coll.getMongo().writeMode() == "commands")
        assert.eq(0, result.nModified, tojson(result));
    assert(result.getWriteError());
    assert(result.getWriteError().errmsg);
    assert(!result.getUpsertedId());
    assert.eq(coll.count(), 1);
    

    https://github.com/mongodb/mongo/blob/b7ff5816f4d9d468b1875013384e7e51184628a0/jstests/core/write_result.js#L116

    写入抛出,因为 {} 不是集合 synchronousEvents 的有效文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多