Java & MongoDB

您所在的位置:网站首页 mongodb删除文档记录 Java & MongoDB

Java & MongoDB

2024-04-26 04:02| 来源: 网络整理| 查看: 265

❮ 上一节 下一节 ❯ Java & MongoDB - 删除文档

要删除集合中的文档,可以使用 collection.deleteOne() 方法删除集合中的特定文档。

collection.deleteOne(filter); 示例

以下是删除文档并显示剩余文档的代码片段 −

import org.bson.Document; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class Tester { public static void main(String[] args) { // Creating a Mongo client MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("myDb"); // Get the collection MongoCollection collection = database.getCollection("sampleCollection"); // Find all documents collection.deleteOne(Filters.eq("First_Name","Mahesh")); System.out.println("Document deleted."); System.out.println("***Documents***"); // Select a particular document FindIterable documents = collection.find(); for (Document document : documents) { System.out.println(document); } } }

现在,让我们编译并运行上面的程序,如下所示。

$javac Tester.java $java Tester 输出

在执行时,上面的程序会有以下输出。

Document deleted. ***Documents*** Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} ❮ 上一节 下一节 ❯


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3