【问题标题】:Multiple updates in MongoDB using java driver使用 java 驱动程序在 MongoDB 中进行多次更新
【发布时间】:2014-02-19 20:04:15
【问题描述】:

我看到了其他几个问题,但其中任何一个都解决了我的问题。

我该怎么做:

UPDATE table SET fiel1 = 'a', field2 = 'b', field3 = 'c' WHERE id='111'

MongoDB中使用java驱动?

【问题讨论】:

    标签: mongodb mongodb-java


    【解决方案1】:

    首先,我认为您需要了解 Mongo shell 脚本的外观。 您的类似 SQL 的查询将转换为以下内容:

    db.table.update({id : '111'},{$set : {fiel1 : 'a', field2 : 'b', field3 : 'c'}})
    

    使用 Java 驱动程序,您将需要以下内容:

    //obtain the collection object:
    DBCollection coll = db.getCollection("table"); //I assume you create your DB-typed db object before
    
    //query DB Object
    DBObject query = new BasicDBObject("id", "111");
    
    //nested DB Object of update object
    DBObject setObj = new BasicDBObject();
    setObj.put("fiel1", "a");
    setObj.put("field2", "b");
    setObj.put("field3", "c");
    
    //update DB Object
    DBObject update = new BasicDBObject("$set", setObj);
    
    coll.update(query, update);
    

    【讨论】:

    • 感谢您的帮助,但使用此代码,我在此行有错误:coll.update(query, update);
    • 感谢您的帮助,它可以正常工作,我了解 Mongo shell 脚本的外观:)
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多