开发者社区 问答 正文

MongoDB 中如何查看被修改的行数

在 Mysql 中可用通过 affect_rows 来查看本次操作数据库中受影响的行数,但是在文本型数据库中怎么获取这些信息呢?Or 别的调试方式?

展开
收起
蛮大人123 2016-02-11 11:19:27 2724 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    db.runCommand({getLastError: 1})
    在输出中 getLastError.n 参数就是受影响的记录。Mongo Manual 是这样定义的:
    n reports the number of documents updated or removed, if the preceding operation was an update or remove operation.
    举例说明:
    在一个 collecton 中有两条如下的记录

    { "_id" : ObjectId("533e5cfa8d6728aef1f00111"), "sex" : "male" }
    { "_id" : ObjectId("533e5d088d6728aef1f00112"), "sex" : "female" }
    先 run 一个 update 操作

    db.people.update({ "sex" : "male" }, { "sex" : "unknown"})
    再 run getLassError 操作

    db.runCommand({getLastError: 1})
    结果如下:

    {

    "updatedExisting" : true,
    "n" : 1,
    "connectionId" : 1332,
    "err" : null,
    "ok" : 1

    }
    update 操作影响了 1 个记录,所以 n 为 1。
    再 run 一个 remove 操作

    db.people.remove()
    结果如下:

    {

    "n" : 2,
    "connectionId" : 1332,
    "err" : null,
    "ok" : 1

    }
    remove 操作影响了 2 个记录,所以 n 为 2。此时 "updatedExisting" : true 未在结果中出现,因为该信息只在 update 操作后出现。

    2019-07-17 18:40:34
    赞同 展开评论