今天学习了mongodb数据库的Java代码连接和编程操作,并成功用java客户端编程连接了mongodb数据库
下面是操作步骤以及代码部分:
(1)添加数据:English:45 Math:89 Computer:100
代码:
public class MongoDBTest {
private MongoClient mongoClient = null;
private MongoDatabase database = null;
@Before
public void init() {
// 连接mongodb服务器,自带连接池效果
mongoClient = MongoClients.create("mongodb://192.168.10.102:27017");
// 获取数据库,如果数据库不存在,为该数据库存储数据是自动创建
database = mongoClient.getDatabase("student");
}
@After
public void close() {
if (mongoClient != null) {
mongoClient.close();
}
}
@Test
public void test01() {
MongoCollection<Document> collection = database.getCollection("student");
Document document = new Document("name", "scofield")
.append("score", new Document("English", 45).append("Math", 89).append("Computer", 100));
collection.insertOne(document);
System.out.println("添加成功");
FindIterable<Document> documents = collection.find();
for (Document document1 : documents) {
System.out.println(document1.toJson());
}
}
}
(2)获取scofield的所有成绩成绩信息(只显示score列)
public class MongoDBTest {
private MongoClient mongoClient = null;
private MongoDatabase database = null;
@Before
public void init() {
// 连接mongodb服务器,自带连接池效果
mongoClient = MongoClients.create("mongodb://49.7.220.30:27017");
// 获取数据库,如果数据库不存在,为该数据库存储数据是自动创建
database = mongoClient.getDatabase("gazikel");
}
@After
public void close() {
if (mongoClient != null) {
mongoClient.close();
}
}
@Test
public void test02() {
MongoCollection<Document> collection = database.getCollection("student");
FindIterable<Document> projection = collection.find(new Document("name", "scofield")).projection(new Document("score", 1).append("_id", 0));
for (Document document : projection) {
System.out.println(document.toJson());
}
}
}