java - Mongo 更新后获取受影响的行

标签 java mongodb

如何指示 Mongo 在更新后返回受影响的行? 目前它返回

{ "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 12 , "updatedExisting" : true}

这意味着 12 条记录已更新,但我想找出它们是哪些记录。

一种解决方法是执行两次查询,首先查找 _id,然后实际更新它们,但这还不够好。

非常感谢

R。

最佳答案

使用findAndModify() API。例如,遵循此博客文章 MongoDB findAndModify() examples using Mongo Shell and Java Driver 中的指南,您可以将更新查询编写为:

    // findAndModify operation. Update colour to blue for cars having speed < 45
    DBObject query = new BasicDBObject("speed",
            new BasicDBObject("$lt", 45));
    DBObject update = new BasicDBObject();
    update.put("$set", new BasicDBObject("color", "Blue"));
    DBCursor cursor = coll.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }
    coll.findAndModify(query, update); 

关于java - Mongo 更新后获取受影响的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720367/

相关文章:

java - 需要递归地从文本文件中打印老板姓名

java - Netty SSL 中的字段长度溢出

java - 读取 java 属性文件,值始终为空

php - 使用 PHP 在 Mongo DB 中的文档中添加数据

node.js - 重复索引的 Mongodb 错误

java - Java 中的异常类

java - 使用 Apache Mina 通过 UDP 将数据发送回客户端

ruby - Mongoid:根据嵌入文档数组的大小进行查询

node.js - MongoDB Mongoose 连接数据库时出错

mongodb - 在 Mongoose 中,Model.find() 和 Model.find().exec() 产生相同的结果。那么为什么还要使用 Model.find().exec() 呢?