MONGODB(三)——Java操作Mongo

相比于java调用MySqlApI来操作数据库,调用Mongo要简洁容易的多。通过一个简单的样例,很容易地就可以上手

一、导入Jar包

添加Monog支持Java的jar包,这里使用的是2.9.3

<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.9.3</version>
</dependency>

二、一个简单的样例

// 连接到mongodb
Mongo mongo = new Mongo("localhost", 27017);
 // 打开数据库test
DB db = mongo.getDB("test");
//获取表,emp为表的名字,若表不存在则会自行创建
DBCollection coll = db.getCollection("emp");
//创建记录对象,append的作用是添加属性值
BasicDBObject doc = new BasicDBObject("name", "fzj").append("sex",
				"man");
//在数据库表中添加记录
coll.insert(doc);

三、自己写的接口实现类(CURD)

通过上面的简单样例,只要接触过数据库和了解一些Mongo的语法。相信接口实现类很容易看懂

public class DBImpl implements DBTool {

	static DB db;
	static {

		Mongo mongo;
		try {
			mongo = new Mongo("localhost", 27017);
			db = mongo.getDB("test");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void insert(String tableName, BasicDBObject dbObject)
			throws UnknownHostException {
		DBCollection coll = db.getCollection(tableName);
		coll.insert(dbObject);
	}

	@Override
	public void delete(String tableName, BasicDBObject dbObject)
			throws UnknownHostException {
		DBCollection coll = db.getCollection(tableName);
		coll.remove(dbObject);
	}

	@Override
	public void update(String tableName, BasicDBObject docFind,
			BasicDBObject doc) throws UnknownHostException {
		DBCollection coll = db.getCollection(tableName);
		coll.update(docFind, doc);
	}

	@Override
	public DBObject find(String tableName, BasicDBObject dbObject)
			throws UnknownHostException {
		DBCollection coll = db.getCollection(tableName);
		return (DBObject) coll.find();
	}

}

参考

[1] 《mongodb-java-driver基本用法》 http://www.cnblogs.com/yjmyzz/p/3865175.html

上一篇:Nodejs学习笔记(四)--- 与MySQL交互(felixge/node-mysql)


下一篇:理解SQL Server是如何执行查询的 (3/3)