【MongoDB数据库】Java MongoDB CRUD Example

时间:2024-01-04 08:06:50

上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example。利用Java连接MongoDB数据库,并实现创建数据库、获取表、遍历表中的对象、对表中对象进行CRUD操作等例程。

1、下载MongoDB Java 支持驱动包

【gitHub下载地址】https://github.com/mongodb/mongo-java-driver/downloads

2、建立Javaproject,并导入jar包

3、连接本地数据库server

在控制面板中开启Mongodb服务,详细操作可參考【MongoDB数据库】怎样安装、配置MongoDB

		try {
mongo = new MongoClient("localhost", 27017);// 保证MongoDB服务已经启动
db = mongo.getDB("andyDB");// 获取到数据库
} catch (UnknownHostException e) {
e.printStackTrace();
}

3、遍历全部的数据库名

public class DBConnection extends TestCase {

	private MongoClient mongo;
private DB db ; @Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
try {
mongo = new MongoClient("localhost", 27017);// 保证MongoDB服务已经启动
db = mongo.getDB("andyDB");// 获取到数据库andyDB
} catch (UnknownHostException e) {
e.printStackTrace();
}
} public void testGetAllDB() {
List<String> dbs = mongo.getDatabaseNames();// 获取到全部的数据库名
for (String dbname : dbs) {
System.out.println(dbname);
}
}
}

4、获取到指定数据库

       DB db = mongo.getDB("andyDB");// 获取到数据库

5、遍历数据库中全部的表名

在DBConnection測试类中加入例如以下測试方法就可以:

	public void testGetAllTables() {
Set<String> tables = db.getCollectionNames();
for (String coll : tables) {
System.out.println(coll);
}
}

6、获取到指定的表

DBCollection table = db.getCollection("person");

7、遍历表中全部的对象

public void testFindAll(){
DBCollection table = db.getCollection("person");
DBCursor dbCursor = table.find();
while(dbCursor.hasNext()){
DBObject dbObject = dbCursor.next();
//打印该对象的特定字段信息
System.out.println("name:"+ dbObject.get("name")+",age:"+dbObject.get("age"));
//打印该对象的全部信息
System.out.println(dbObject);
}
}

Console窗体打印消息:

name:jack,age:50.0

{ "_id" : { "$oid" : "537761da2c82bf816b34e6cf"} , "name" : "jack" , "age" : 50.0}

name:小王,age:24

{ "_id" : { "$oid" : "53777096d67d552056ab8916"} , "name" : "小王" , "age" : 24}

8、保存对象

1)保存对象方法一

	public void testSave() {
DBCollection table = db.getCollection("person");
BasicDBObject document = new BasicDBObject();
document.put("name", "小郭");// 能直接插入汉字
document.put("age", 24);//"age"相应的值是int型
table.insert(document);
}

在mongodb shell中使用命令查看数据

> db.person.find()

{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }

{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }

{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }

2)保存对象方法二

	public void testSave2() {
DBCollection table = db.getCollection("person");
BasicDBObject document = new BasicDBObject();//能够加入多个字段
document.put("name", "小张");// 能直接插入汉字
document.put("password", "xiaozhang");// 多加入一个字段也是能够的,由于MongoDB保存的是对象。
document.put("age", "23");//"age"相应的值是String
table.insert(document);
}

在mongodb shell中使用命令查看数据

> db.person.find()

{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }

{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }

{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }

{ "_id" : ObjectId("53777230d67dfe576de5079a"), "name" : "小张", "password" : "xiaozhang", "age" : "23" }

3)保存对象方法三通过加入Map集合的方式加入数据到BasicDBObject

	public void testSave3(){
DBCollection table = db.getCollection("person"); Map<String,Object> maps = new HashMap<String,Object>();
maps.put("name", "小李");
maps.put("password", "xiaozhang");
maps.put("age", 24); BasicDBObject document = new BasicDBObject(maps);//这样加入后,对象里的字段是无序的。 table.insert(document);
}

在mongodb shell中使用命令查看数据

> db.person.find()

{ "_id" : ObjectId("537761da2c82bf816b34e6cf"), "name" : "jack", "age" : 50 }

{ "_id" : ObjectId("53777096d67d552056ab8916"), "name" : "小王", "age" : 24 }

{ "_id" : ObjectId("5377712cd67d84f62c65c4f6"), "name" : "小郭", "age" : 24 }

{ "_id" : ObjectId("53777230d67dfe576de5079a"), "name" : "小张", "password" : "xiaozhang", "age" : "23" }

{ "_id" : ObjectId("537772e9d67df098a26d79a6"), "age" : 24, "name" : "小李", "password" : "xiaozhang" }

9、更新对象

我们能够结合【mongodb shell命令】db.person.update({name:"小李"},{$set:{password:"hello"}})来理解Java是怎样操作对象来更新的。{name:"小李"}是一个BasicDBObject,{$set:{password:"hello"}也是一个BasicDBObject。这样理解的话。你就会认为mongodb
shell命令操作和Java操作非常相似。

	public void testUpdate() {
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject();
query.put("name", "小张"); BasicDBObject newDocument = new BasicDBObject();
newDocument.put("age", 23); BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
} // 命令操作:db.person.update({name:"小李"},{$set:{password:"hello"}})
public void testUpdate2() {
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject("name", "小张");
BasicDBObject newDocument = new BasicDBObject("age", 24);
BasicDBObject updateObj = new BasicDBObject("$set", newDocument);
table.update(query, updateObj);
}

10、删除对象

可參考db.users.remove({name:"小李"})命令来理解Java操作对象

	public void testDelete(){
DBCollection table = db.getCollection("person");
BasicDBObject query = new BasicDBObject("name", "小李");
table.remove(query);
}

11、參考

Java + MongoDB Hello World Example(推荐)

12、你可能感兴趣

【MongoDB数据库】怎样安装、配置MongoDB

【MongoDB数据库】MongoDB 命令入门初探

转载请注明出处:http://blog.csdn.net/andie_guo/article/details/26098331,谢谢!

版权声明:本文博客原创文章。博客,未经同意,不得转载。