如何使用Java更新MongoDB集合中的多个文档?
使用updateMany()方法可以更新集合的所有文档。
语法
db.COLLECTION_NAME.update(<filter>, <update>)
在Java中,com.mongodb.client.MongoCollection接口为您提供了一个具有相同名称的方法。使用此方法,您可以一次更新集合中的多个文档,为此,您需要传递更新的过滤器和值。
示例
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 org.bson.conversions.Bson; import com.mongodb.MongoClient; public class UpdatingMultipleDocuments { 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", "Delhi"); Document document3 = new Document("name", "Rahim").append("age", 30).append("city", "Delhi"); //插入创建的文档 List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); list.add(document3); collection.insertMany(list); System.out.println("List of the documents: "); FindIterable<Document> iterDoc = collection.find(); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } //更新多个文档 Bson filter = new Document("city", "Delhi"); Bson newValue = new Document("city", "Vijayawada"); Bson updateOperationDocument = new Document("$set", newValue); collection.updateMany(filter, updateOperationDocument); System.out.println("Document update successfully..."); System.out.println("List of the documents after update"); iterDoc = collection.find(); it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
输出结果
List of the documents: Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}} Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Delhi}} Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Delhi}} Document update successfully... List of the documents after update Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}} Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Vijayawada}} Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Vijayawada}}