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

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

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


update 语句返回的 json 中,键为 n 的值就是被修改的行数。
打印出来自己看吧、


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 操作后出现。

【热门文章】
【热门文章】