全是干货的技术殿堂


文章收录在我的 GitHub 仓库,欢迎Star/fork:​

Java-Interview-Tutorial

https://github.com/Wasabi1234/Java-Interview-Tutorial


mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们现在来使用mongodb-driver完成对Mongodb的操作。

1 环境准备

创建工程,并添加以下依赖:

<dependency> 
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.10.1</version>
</dependency>

2 使用mongodb-driver

2.1 查询所有

@Test 
public void test1() {
//创建连接
MongoClient client = new MongoClient("192.168.200.128");
//打开数据库
MongoDatabase commentdb = client.getDatabase("commentdb");
//获取集合
MongoCollection<Document> comment = commentdb.getCollection("comment");
//查询
FindIterable<Document> documents = comment.find();
//查询记录获取文档集合
for (Document document : documents) {
System.out.println("_id:" + document.get("_id"));
System.out.println("内容:" + document.get("content"));
System.out.println("用户ID:" + document.get("userid"));
System.out.println("点赞数:" + document.get("thumbup")); }
//关闭连接
client.close();
}
}

2.2 根据_id查询

每次使用都要用到MongoCollection,进行抽取:

private MongoClient client; 
private MongoCollection<Document> comment;
@Before
public void init() {
//创建连接
client = new MongoClient("192.168.200.128");
//打开数据库
MongoDatabase commentdb = client.getDatabase("commentdb");
//获取集合
comment = commentdb.getCollection("comment");
}

@After
public void after() {
client.close();
}


@Test public void test2() {
//查询
FindIterable<Document> documents = comment.find(new BasicDBObject("_id", "1"));
//查询记录获取文档集合
for (Document document : documents) {
System.out.println("_id:" + document.get("_id"));
System.out.println("内容:" + document.get("content"));
System.out.println("用户ID:" + document.get("userid"));
System.out.println("点赞数:" + document.get("thumbup"));
}
}

2.3 新增

@Test public void test3() { 
Map<String, Object> map = new HashMap();
map.put("_id", "6");
map.put("content", "很棒!");
map.put("userid", "9999");
map.put("thumbup", 123);
Document document = new Document(map);
comment.insertOne(document);
}

2.4 修改

@Test public void test4() { 
//修改的条件
Bson filter = new BasicDBObject("_id", "6");
//修改的数据
Bson update = new BasicDBObject("$set", new Document("userid", "8888"));
comment.updateOne(filter, update);
}

2.5 删除

@Test public void test5() { 
//删除的条件
Bson filter = new BasicDBObject("_id", "6");
comment.deleteOne(filter);
}

mongodb-driver使用_mongodb