首先在项目中添加下面的依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.10.1</version>
</dependency>
完整代码:
import com.mongodb.BasicDBObject;
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;
import java.util.HashMap;
/**
* @author :had
* @date :Created in 2020/09/28 0028 下午 03:18;20
*/
public class MongodbTest {
private MongoClient client;
private MongoDatabase commentdb;
private MongoCollection<Document> comment;
@Before
public void before() {
//创建连接
client = new MongoClient("192.168.247.129");
//打开数据库
commentdb = client.getDatabase("commentdb");
//获取集合
comment = commentdb.getCollection("comment");
}
//查询所有
@Test
public void test1() {
//查询
FindIterable<Document> documents = comment.find();
for (Document document : documents) {
System.out.println(document.get("_id"));
System.out.println(document.get("name"));
}
}
//条件查询
@Test
public void test2(){
//封装查询条件
BasicDBObject bson=new BasicDBObject("_id","123");
//查询
FindIterable<Document> documents=comment.find(bson);
for (Document document : documents) {
System.out.println("-----------------------------");
System.out.println(document.get("_id"));
System.out.println(document.get("name"));
}
}
//新增
@Test
public void test3(){
//封装
HashMap<String,Object> map = new HashMap<>();
map.put("_id","4");
map.put("name","今天天气好晴朗!!!");
Document document = new Document(map);
comment.insertOne(document);
}
//修改
@Test
public void test4(){
//修改的条件
BasicDBObject filter=new BasicDBObject("_id","4");
//修改的内容
BasicDBObject update=new BasicDBObject("$set",new Document("userId","8888"));
comment.updateOne(filter, update);
}
//删除
@Test
public void test5(){
//删除的条件
BasicDBObject filter = new BasicDBObject("_id", "123");
comment.deleteOne(filter);
}
@After
public void after() {
//关闭连接
client.close();
}
}