How to update MongoDb database in Java?

佐手、 提交于 2021-02-07 21:35:26

问题


I'm newbie with the MongoDb, there are a lot of examples about updating a collection in 2.x versions but I couldn't find any source about 3.x versions.

JAVA CODE:

    MongoClient mongoClient = new MongoClient("localhost",27017);
    MongoDatabase database = mongoClient.getDatabase("dbTest");
    MongoCollection<Document> collection =    database.getCollection("colTest");
    Document updateQuery = new Document();
    updateQuery.append("$set",
    new Document().append("_id", "test"));
    Document searchQuery = new Document();
    searchQuery.append("likes", "125");
    collection.updateMulti(searchQuery, updateQuery); //.updateMulti gives an error.

There isn't any updateMulti in 3.x so how can I check the id of the database and change one of the datas?

Example MongoDB:

 { 
"_id" : "test",
   "status" : 2,
   "time" : null,
   "instagram" :{
         "description" : "database",
         "likes" : 100,
         "url" : "http://www.instagram.com/",
         "by", "users"
   },
   "batchid" : 15000234
}

Expected Output:

{ 
   "_id" : "test",
   "status" : 1,
   "time" : null,
   "instagram" :{
         "description" : "database",
         "likes" : 125,
         "url" : "http://www.instagram.com/",
         "by", "users"
   },
   "batchid" : 15000234
}

回答1:


For Mongodb-java driver:

Use updateOne method To update single Document within the collection based on the filter,

         collection.updateOne(searchQuery, updateQuery );

Use updateMany method, To Update multiple Documents within the collection based on the filter ,

         collection.updateMany(searchQuery, updateQuery );

Example,

        MongoClient client = new MongoClient("localhost",27017);
        MongoDatabase db = client.getDatabase("TestDB");
        MongoCollection<Document> collection = db.getCollection("test");
        Document query = new Document();
        query.append("_id","test");
        Document setData = new Document();
        setData.append("status", 1).append("instagram.likes", 125);
        Document update = new Document();
        update.append("$set", setData);
        //To update single Document  
        collection.updateOne(query, update);


来源:https://stackoverflow.com/questions/42433341/how-to-update-mongodb-database-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!