Java基础、中级、高级、架构面试资料

详解 com.mongodb.client.MongoCollection 的用法!

JAVA herman 8725浏览
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

MongoDB 非常的简单,又非常的复杂。简单的是增删改查简单,难的是完全理解、学会并在生产中应用,部署,运维等。我们今天先来个简单的,从 MongoCollection 开始学起。

com.mongodb.client.MongoCollection 是一个接口。在 MongoDB 的驱动包里面,它只有一个实现类 com.mongodb.MongoCollectionImpl。

MongoCollection 顾名思义,它代表的就是一个 Mongo 的集合。一个集合 Collection 就相当于 MySQL 中的一张表。我们对 Mongo 的操作,基本上都是基于 Collection 来进行的。

MongoCollection 接口上又一个 @ThreadSafe 注解,这个注解的作用,我们后面单独来写。今天我们主要任务是 MongoCollection。

MongoCollection 接口中有非常多的方法,我主要介绍几个常用的方法。剩下的大家自己去摸索摸索。

要使用 MongoCollection 我们必须的先找到对应的数据库 MongoDatabase。使用 MongoDatabase 又必须要建立一个连接 MongoClient。下面我们看一个获取 MongoCollection 的实例:

public class XttblogMongoDBJDBC{
   public static void main( String args[] ){
      try{   
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017);
       
        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("xttblog");  
        System.out.println("Connect to database successfully");
      
        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 选择成功");
      }catch(Exception e){
        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}

前面我说过了,MongoCollection 就相当于一张表。获取到了 MongoCollection 我们就可以增删改查文档了。

插入文档

使用 com.mongodb.client.MongoCollection 类的 insertMany() 方法来插入一个文档。

/** 插入文档  
 * 1. 创建文档 org.bson.Document 参数为key-value的格式 
 * 2. 创建文档集合List<Document> 
 * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) 
 * */
Document document = new Document("title", "MongoDB").  
append("description", "database").  
append("likes", 100).  
append("by", "www.xttblog.com");  
List<Document> documents = new ArrayList<Document>();  
documents.add(document);  
// MongoCollection<Document> collection = mongoDatabase.getCollection("test");
collection.insertMany(documents);  
System.out.println("文档插入成功");  

检索查询文档

使用 com.mongodb.client.MongoCollection 类中的 find() 方法来获取集合中的所有文档。

/**检索所有文档  
 * 1. 获取迭代器FindIterable<Document> 
 * 2. 获取游标MongoCursor<Document> 
 * 3. 通过游标遍历检索出的文档集合 
 * */  
FindIterable<Document> findIterable = collection.find();  
MongoCursor<Document> mongoCursor = findIterable.iterator();  
while(mongoCursor.hasNext()){  
   System.out.println(mongoCursor.next());  
}  

更新修改文档

使用 com.mongodb.client.MongoCollection 类中的 updateMany() 方法来更新集合中的文档。

//更新文档   将文档中likes=100的文档修改为likes=200   
collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));  
//检索查看结果  
FindIterable<Document> findIterable = collection.find();  
MongoCursor<Document> mongoCursor = findIterable.iterator();  
while(mongoCursor.hasNext()){  
   System.out.println(mongoCursor.next());  
}  

删除文档

删除文档,可以使用 deleteOne() 或者 deleteMany() 等方法。

//删除符合条件的第一个文档  
collection.deleteOne(Filters.eq("likes", 200));  
//删除所有符合条件的文档  
collection.deleteMany (Filters.eq("likes", 200));  
//检索查看结果  
FindIterable<Document> findIterable = collection.find();  
MongoCursor<Document> mongoCursor = findIterable.iterator();  
while(mongoCursor.hasNext()){  
  System.out.println(mongoCursor.next());  
}  

MongoCollection 类中还有非常多的方法,包括重命名集合 dropIndexes(),删除索引 renameCollection() 等。

参考资料

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » 详解 com.mongodb.client.MongoCollection 的用法!