日期:2014-05-16 浏览次数:20428 次
1. 下载 MongoDB, Java Driver
?
下载地址:http://www.mongodb.org/downloads
?
下载地址:https://github.com/mongodb/mongo-java-driver/downloads
?
2. 安装 MongoDB
?
查看快速上手文档: http://www.mongodb.org/display/DOCS/Quickstart
?
下载后解压即可。 直接运行:mongod.exe 即可启动 MongoDB,非常小巧,方便
?
3. 增加安全权限
?
由于直接启动 MongoDB 后,没有账号权限限制,不太安全。 为了安全起见,可以增加权限限制
?
执行以下命令启动MongoDB
?
mongod --dbpath ../data/db #"--dbpath" 为数据文件的存储位置?
安全方面的设置可以查看文档:http://www.mongodb.org/display/DOCS/Security+and+Authentication
?
use my_mongo #默认进入test 数据库,切换为 my_mongo db.addUser("prx", "prx123456") #创建my_mongo数据库的账号,密码 db.system.users.find() #查看刚才创建的账号
?
重新启动 MongoDB ,增加权限检查
mongod --dbpath ../data/db --auth #"--auth" 表示需要账号验证
?
4. Java代码示例
?
package prx.mongo; import java.net.UnknownHostException; import java.util.Date; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; public class Test { static DBCollection coll = null; static DB db = null; static { Mongo m = null; try { m = new Mongo("localhost", 27017); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } db = m.getDB("my_mongo"); if (db.authenticate("prx", "prx123456".toCharArray())) { System.out.println("auth success"); } } public static void main(String[] args) throws Exception { // getMemo(); // insertMemo(); query(); // delete(); } /** * * @param collectionName 相当于 Table 名 * @return * @throws Exception */ public static DBCollection getDBCollection(String collectionName) throws Exception { if(coll == null) { coll = db.getCollection(collectionName); } return coll; } public static void insertMemo() throws Exception { DBCollection coll = getDBCollection("member"); BasicDBObject doc = new BasicDBObject(); doc.put("name", "prx"); doc.put("city", "changsha"); doc.put("time", new Date()); coll.insert(doc); } public static void getMemo() throws Exception { DBCollection coll = getDBCollection("member"); BasicDBObject obj = (BasicDBObject) coll.findOne(); System.out.println(obj); } public static void query() throws Exception { DBCollection coll = getDBCollection("member"); BasicDBObject obj = new BasicDBObject(); obj.put("name", "prx"); DBCursor cursor = coll.find(obj); while (cursor.hasNext()) { Date date = (Date) cursor.next().get("time"); System.out.println(date); } cursor.close(); } public static void delete() throws Exception { DBCollection coll = getDBCollection("member"); BasicDBObject query = new BasicDBObject(); query.put("name", "prx"); // 找到并且删除,并返回删除的对象 DBObject removeObj = coll.findAndRemove(query); System.out.println(removeObj); } }?