欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mongodb最新java驱动CRUD使用演示

程序员文章站 2022-05-24 08:49:45
...

    今天使用java代码调用mongodb数据库,用maven引入了最新版的mongodb驱动,在网上找了demo结果发现将demo贴到eclipse上之后好多过期方法。所以猜想mongodb驱动版本肯定有很大的更新。

    果不其然,mongodb的确有了最新版3.x。而网上几乎所有的demo都基于2.x版本。下面是在github上找的一些资料,再结合官方文档总结的3.x版本的CRUD操作。

 

    以下演示源码地址:https://github.com/smallbug-vip/repo

 

首先在pom.xml中配置引入jar包:

<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>3.2.1</version>
		</dependency>

 下面演示会使用到一些静态方法,eclipse中使用快捷键不能自动导包,可以手动添加:

import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Filters.gt;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lt;
import static com.mongodb.client.model.Filters.lte;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.include;
import static com.mongodb.client.model.Sorts.descending;

 准备工作:

MongoDatabase db = null;
	MongoClient client = null;

	@Before
	public void before() {
		client = new MongoClient("192.168.88.132", 27017);
		db = client.getDatabase("its");
	}

	@After
	public void after() {
		if (client != null) {
			client.close();
		}
	}

 获取连接:

@Test
	public void testCollections() {

		MongoIterable<String> collections = db.listCollectionNames();
		MongoCursor<String> cu = collections.iterator();
		for (; cu.hasNext();) {
			System.out.println(cu.next());
		}
	}

  测试增加一个Document:

@Test
	public void testAdd() {
		MongoCollection<Document> col = db.getCollection("s1");
		Document doc = new Document("name", "MongoDB")//
				.append("type", "database")//
				.append("count", 1)//
				.append("info", new Document("x", 203).append("y", 102));
		col.insertOne(doc);
	}

 测试增加多个Document:

@Test
	public void testAddALL() {
		MongoCollection<Document> col = db.getCollection("s1");
		List<Document> dos = new ArrayList<Document>();
		for (int i = 0; i < 100; i++) {
			dos.add(new Document("i", i));
		}
		col.insertMany(dos);
	}

 查看当前有多少记录:

@Test
	public void testCount() {
		MongoCollection<Document> col = db.getCollection("s1");
		System.out.println(col.count());
	}

 获取第一条记录:

@Test
	public void testFirst() {
		MongoCollection<Document> col = db.getCollection("s1");
		Document myDoc = col.find().first();
		System.out.println(myDoc.toJson());
	}

 获取第所有记录:

@Test
	public void testFindAll() {
		MongoCollection<Document> col = db.getCollection("s1");
		/**************** 第一种方法 *********************/
		// MongoCursor<Document> cursor = col.find().iterator();
		// while (cursor.hasNext()) {
		// System.out.println(cursor.next().toJson());
		// }
		/**************** 第二种方法 *********************/
		for (Document cur : col.find()) {
			System.out.println(cur.toJson());
		}
	}

 分页:

@Test
	public void testLimit() {
		MongoCollection<Document> col = db.getCollection("s1");
		for (Document cur : col.find().skip(20).limit(10)) {
			System.out.println(cur.toJson());
		}
	}

 条件查询:

@Test
	public void testFilter() {
		MongoCollection<Document> col = db.getCollection("s1");
		// eq为静态导入
		Document myDoc = col.find(eq("i", 71)).first();
		System.out.println(myDoc.toJson());
	}

 获得子集:

@Test
	public void testBlock() {
		MongoCollection<Document> col = db.getCollection("s1");
		Block<Document> printBlock = new Block<Document>() {
			@Override
			public void apply(final Document document) {
				System.out.println(document.toJson());
			}
		};
		col.find(and(gt("i", 50), lte("i", 80))).forEach(printBlock);
	}

 排序:

@Test
	public void testSort() {
		MongoCollection<Document> col = db.getCollection("s1");
		// 升序 ascending
		FindIterable<Document> it = col.find(exists("i")).sort(descending("i"));
		for (Document d : it) {
			System.out.println(d.toJson());
		}
	}

 筛选字段:

@Test
	public void testProjection() {
		MongoCollection<Document> col = db.getCollection("s1");
		FindIterable<Document> it = col.find()//
				.projection(and(include("name"), excludeId()));
		for (Document d : it) {
			System.out.println(d.toJson());
		}
	}

 更新一条Document:

@Test
	public void testUpdateOne() {
		MongoCollection<Document> col = db.getCollection("s1");
		col.updateOne(//
				eq("i", 10), new Document("$set", new Document("i", 110)));
	}

 更新多条记录:

@Test
	public void testUpdateMany() {
		MongoCollection<Document> col = db.getCollection("s1");
		// $inc 自增
		UpdateResult updateResult = col.updateMany(lt("i", 10), new Document("$inc", new Document("i", 234)));
		System.out.println(updateResult.getModifiedCount());
	}

 测试删除一条Document:

@Test
	public void testDeleteOne() {
		MongoCollection<Document> col = db.getCollection("s1");
		DeleteResult re = col.deleteOne(eq("i", 234));
		System.out.println(re.getDeletedCount());
	}

 测试删除多条Document:

@Test
	public void testDeleteMany() {
		MongoCollection<Document> col = db.getCollection("s1");
		DeleteResult deleteResult = col.deleteMany(gte("i", 100));
		System.out.println(deleteResult.getDeletedCount());
	}