mongodb入门-3-Java中使用mongodb
2022/3/27 2:22:34
本文主要是介绍mongodb入门-3-Java中使用mongodb,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
无spring使用mongodb
导入依赖
版本我选择的是<mongo-driver-version>3.12.10</mongo-driver-version>
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies>
API的简单使用
package com.twc; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.conversions.Bson; import org.junit.Test; import java.util.Random; public class MongoJDBC { public static MongoDatabase getDataBase(String db){ MongoClient client = new MongoClient("localhost", 27017); return client.getDatabase(db); } String dbName = "mydb"; String collName = "c3"; @Test public void testCreateCollection(){ MongoDatabase dataBase = getDataBase(dbName); dataBase.createCollection(collName); } @Test public void testInsert(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); for (int i = 0; i < 100; i++) { coll.insertOne(new Document("name", "name" + new Random().nextInt(10000)) .append("age", 15 + new Random().nextInt(40)) .append("gender", new Random().nextBoolean() ? "female" : "male")); } } @Test public void testFind(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); printAll(coll); } @Test public void updateMany(){ MongoDatabase dataBase = getDataBase(dbName); MongoCollection<Document> coll = dataBase.getCollection(collName); //将18以上的标记为成年,以下的为未成年 Bson gte18 = Filters.gte("age", 18); coll.updateMany(gte18, new Document("$set", new Document("adult", true))); //将18以上的标记为成年,以下的为未成年 Bson lt18 = Filters.lt("age", 18); coll.updateMany(lt18, new Document("$set", new Document("adult", false))); printAll(coll); System.out.println("-----DeleteMany"); coll.deleteMany(Filters.eq("gender", "female")); printAll(coll); } private void printAll(MongoCollection<Document> coll) { FindIterable<Document> documents = coll.find(); for (Document document : documents) { System.out.println(document); } } }
springboot使用mongodb
这篇关于mongodb入门-3-Java中使用mongodb的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-16使用vue3+springboot构建简单Web应用教程
- 2024-11-15全栈开发项目实战:从入门到初级项目的实现
- 2024-11-15数据库项目实战:从入门到初级应用教程
- 2024-11-15IDEA项目实战入门教程
- 2024-11-15IT编程项目实战:新手入门的全面指南
- 2024-11-15Java开发项目实战:新手入门与初级技巧
- 2024-11-15Java零基础项目实战:从入门到独立开发
- 2024-11-15MyBatis Plus教程:入门与基础操作详解
- 2024-11-15MyBatis-Plus教程:新手入门与实战技巧
- 2024-11-15MyBatis教程:从入门到实践