【问题标题】:MongoDB update using Java 3 driver使用 Java 3 驱动程序更新 MongoDB
【发布时间】:2015-04-03 14:35:34
【问题描述】:

我正在切换到 MongoDB Java 驱动程序版本 3。我不知道如何执行文档更新。例如,我想更改用户的“年龄”:

MongoDatabase db = mongoClient.getDatabase("exampledb");
MongoCollection<org.bson.Document> coll = db.getCollection("collusers");

Document doc1 = new Document("name", "frank").append("age", 55) .append("phone", "123-456-789");
Document doc2 = new Document("name", "frank").append("age", 33) .append("phone", "123-456-789");
coll.updateOne(doc1, doc2); 

输出是:

java.lang.IllegalArgumentException: Invalid BSON field name name

知道如何解决吗? 谢谢!

【问题讨论】:

    标签: mongodb-java


    【解决方案1】:

    用途:

    coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
    

    用于更新找到的第一个文档。对于多个更新:

    coll.updateMany(eq("name", "frank"), new Document("$set", new Document("age", 33)));
    

    在这个链接上,你可以罚款quick reference to MongoDB Java 3 Driver

    【讨论】:

    • 什么什么什么??? $set 是吉法!!!谁想到了这个隐含/隐藏的指令?与其他我不知道隐式/隐藏指令相比,它实际上意味着什么?
    • @AlikElzin-kilaka,我不知道“Jiffa”是什么意思,但我确信我们非常同意将 set 命令传递给服务器的疯狂方式。驱动程序应该已经包裹了$set$inc 等。
    • @Paul 日本国际货运代理协会,显然。
    • 如何使用辅助函数来实现? eq(...), set(new Document("age",33)) 似乎由于某种原因不起作用
    【解决方案2】:

    在 Mongodb Java driver 3.0 中,更新文档时,可以调用 coll.replaceOne 方法替换文档,或者调用 coll.updateOne / coll.updateMany 方法通过 $set/$ 更新文档setOnInsert/etc 运算符。

    在你的情况下,你可以尝试:

    coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
    coll.replaceOne(eq("name", "frank"), new Document("age", 33));
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

      coll.findOneAndReplace(doc1, doc2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多