的更新()方法中的现有文档中更新的值。
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
在Java中,可以使用com.mongodb.client.MongoCollection接口的updateOne()方法更新单个文档。对于此方法,您需要传递更新的过滤器和值。
import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; public class UpdatingDocuments { public static void main( String args[] ) { //创建一个Mongo客户端 MongoClient mongo = new MongoClient( "localhost" , 27017 ); //连接到数据库 MongoDatabase database = mongo.getDatabase("myDatabase"); //创建一个收集对象 MongoCollection<Document>collection = database.getCollection("myCollection"); //准备文件 Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad"); Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam"); Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi"); //插入创建的文档 List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); list.add(document3); collection.insertMany(list); //更新文件 collection.updateOne(Filters.eq("name", "Robert"), Updates.set("city", "Delhi")); System.out.println("Document update successfully..."); FindIterable<Document> iterDoc = collection.find(); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
输出结果
Document update successfully... Document after update: Document{{_id=5e86dd21e9b25f3460b1abe0, name=Ram, age=26, city=Hyderabad}} Document{{_id=5e86dd21e9b25f3460b1abe1, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e86dd21e9b25f3460b1abe2, name=Rhim, age=30, city=Delhi}}