如何在 Java 中更新 MongoDb 数据库?

问题描述:

我是 MongoDb 的新手,有很多关于在 2.x 版本中更新集合的示例,但我找不到关于 3.x 版本的任何来源.

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 代码:

    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.

3.x 中没有任何 updateMulti,那么我如何检查数据库的 id 并更改其中一个数据?

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

示例 MongoDB:

Example MongoDB:

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

预期输出:

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

对于 Mongodb-java 驱动程序:

For Mongodb-java driver:

使用updateOne方法要根据过滤器更新集合中的单个文档,

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

         collection.updateOne(searchQuery, updateQuery );

使用updateMany方法,要根据过滤器更新集合中的多个文档,

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

         collection.updateMany(searchQuery, updateQuery );

示例,

        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);