问题
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