一、依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.5.0</version>
</dependency>
二、编码
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import org.junit.Test;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongodbTest {
@Test
public void testConnection() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
System.out.println(database.getName());
}
@Test
public void testCreateCollection() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("article");
System.out.println("创建集合成功!!");
}
@Test
public void testInsert() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("article");
Document doc = new Document("_id", 1).append("title", "first article")
.append("content", "hello world").append("author", "Jack")
.append("createDate", new Date());
collection.insertOne(doc);
Document temp = null;
List<Document> list = new ArrayList<Document>();
for (int i = 2; i < 6; i++) {
temp = new Document("_id", i).append("title", "first article" + i)
.append("content", "hello world" + i)
.append("author", "Jack").append("createDate", new Date());
list.add(temp);
}
collection.insertMany(list);
}
@Test
public void testUpdate() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("article");
collection.updateOne(Filters.eq("_id", 1), new Document("$set",new Document("title", "article1")));
}
@Test
public void testDelete() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("article");
collection.deleteOne(Filters.eq("_id", 5));
}
@Test
public void testQuery() {
MongoClient mongoClient = new MongoClient("192.168.2.23", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("article");
collection.find().forEach(new Block<Document>() {
public void apply(Document doc) {
System.out.println(doc.toJson());
}
});
}
}