一、pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>A01mongodb</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.12.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.9</source> <target>1.9</target> </configuration> </plugin> </plugins> </build> </project>
二、测试
package com.wuxi.test; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MyTest { private MongoDatabase student = null; private MongoClient client = null; @Before public void before() { //链接mongo服务器 client = new MongoClient("127.0.0.1"); //得到要操作的数据库 student = client.getDatabase("student"); } @After public void after() { client.close(); } @Test public void test01() { //得到要操作的表 MongoCollection<Document> persons = student.getCollection("person"); //操作表 //查询所有 FindIterable<Document> documents = persons.find(); for (Document document : documents) { String str = "{_id:" + document.getString("_id") + ",name:" + document.getString("name") + ",age:" + document.getInteger("age") + "}"; System.out.println(str); } /* //简单条件查询 BasicDBObject bson = new BasicDBObject("name", "mengmeiqi"); FindIterable<Document> documents = persons.find(bson); for (Document document : documents) { String str = "{_id:" + document.getString("_id") + ",name:" + document.getString("name") + ",age:" + document.getInteger("age") + "}"; System.out.println(str); } //复杂条件查询 BasicDBObject bson = new BasicDBObject("age", new BasicDBObject("$lt", 20)); FindIterable<Document> documents = persons.find(bson); for (Document document : documents) { String str = "{_id:" + document.getString("_id") + ",name:" + document.getString("name") + ",age:" + document.getInteger("age") + "}"; System.out.println(str); } //添加数据 Map<String, Object> map = new HashMap<>(); map.put("_id", "6"); map.put("name", "baixiaowu"); map.put("age", 27); Document document = new Document(map); persons.insertOne(document); */ } }
原文:https://www.cnblogs.com/linding/p/13723568.html