MongoDB Java Driver初试

本文介绍如何使用MongoDB Java Driver进行数据库的基本操作,包括连接服务、数据库及集合的管理、文档的增删改查等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB Java Driver可以使Java能够操作MongoDB,从而进行增删改查等操作。

参考:

 

需要先安装mongo-java-driver:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/

或者:https://mongodb.github.io/mongo-java-driver/

 

将此包导入到项目中即可使用。

基本操作

连接服务:

MongoClient mongoClient = new MongoClient(host, port);

连接数据库:

MongoDatabase mongoDatabase = mongoClient.getDatabase("dbName");

获取集合:

MongoCollection<Document> collection = mongoDatabase.getCollection("cltName");

创建集合:

mongoDatabase.createCollection("cltName");

创建文档:需要导入org.bson.Document

Document document = new Document("key", value).  
         append("key", value).
         append("key", value);  

创建文档集:需要导入java.util.List

List<Document> documents = new ArrayList<Document>();    // 创建文档集
documents.add(document);                                 // 添加文档

向集合插入文档集:

collection.insertMany(documents);

删除文档:需要设置条件,然后才能删除满足条件的文档

collection.deleteOne(Filters.eq("key", val));        // 删除第一条
collection.deleteMany(Filters.eq("key", val));       // 删除所有

修改文档:同样需要设置条件,然后才能修改满足条件的文档

// 修改满足条件的第一条文档
collection.updateOne();

// 修改满足条件的所有文档
collection.updateMany(Filters.eq("key", value), new Document("$set",new Document("newKey",newValue)));

查询文档:

Document myDoc = collection.find(Filters.eq("key", value)).first();    // 获得集合中第一条数据

检索文档:通过游标遍历整个集合

FindIterable<Document> findIterable = collection.find();        // 迭代器
MongoCursor<Document> mongoCursor = findIterable.iterator();    // 游标
while(mongoCursor.hasNext()){                                   // 遍历游标
    System.out.println(mongoCursor.next());
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值