|
本文使用的环境是:win7_64+Eclipse+maven
一、准备工作下载java驱动包
驱动包下载地址:http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
mongoDB下载:http://www.mongodb.org/
在线api:http://docs.mongodb.org/manual/applications/drivers/
二、安装Mongo1.windows下安装方式:
安装Mongo数据库:
第一步:下载安装包:如果是win系统,注意是64位还是32位版本的,请选择正确的版本。
第二步:新建目录“D:\MongoDB”,解压下载到的安装包,找到bin目录下面全部.exe文件,拷贝到刚创建的目录下。
第三步:在“D:\MongoDB”目录下新建“data”文件夹,它将会作为数据存放的根文件夹。
配置Mongo服务端:
打开CMD窗口,按照如下方式输入命令:
> d:
> cd D:\MongoDB
> mongod --dbpath D:\MongoDB\data
启动成功后从浏览器访问:http://localhost:27017/

标明windows下的mongodb已经启动成功;
2.linux安装方式:
下载后解压确保数据库目录大小剩余空间在3G以上;
这里采用配置文件方式启动:在mongodb的根目录创建一个名为:mongodb.conf的文件,内容如下:
- #fork=true #以守护进程的方式运行,创建服务器进程
-
- ##master=true #单主从配置时设为主服务器
-
- ##salve=true ##单主从配置时设为从服务器
-
- #replSet=blort #设置富本集的名字
-
- #shardsvr=true #设置是否分片
-
- #repairpath = /mongodb2.6.3/repair
- #pidfilepath = /mongodb2.6.3/mongodb.pid
- #sysinfo = true
- #verbose = true
- #cpu = true
- #Network and security set
- #Management
- #nohttpinterface = true
- #rest = true
- #syncdelay = 5
-
- #Directory and relavent set
- dbpath = /mongodb2.6.3/data #数据库路径
- logpath = /mongodb2.6.3/logs/mongodb.log #日志输出文件路径
- logappend = true #日志输出方式
- directoryperdb = true
- noauth = true
- port = 8888 #端口号
- maxConns = 1024
- fork = true
- quota = true
- quotaFiles = 1024
- nssize = 16
启动方式如下:/mongodb2.6.3/bin/mongod -f /mongodb2.6.3/mongodb.conf
记得开启linux的访问端口:
#vi /etc/sysconfig/iptables
yy复制一行
p粘贴
修改端口
#service iptables restart
设置开机自启动
#echo /mongodb2.6.3/bin/mongod -f /mongodb2.6.3/mongodb.config >>/etc/rc.local

数据库启动完成,接下来是创建数据库和集合:
mongo --port 8888
> show dbs
admin (empty)
local 0.078GB
> use admin(切换管理用户)
switched to db admin
> db.mymongo(创建数据库)
admin.mymongo
> db.addUser("root","root")(添加用户)
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
> db.auth("root","root")(添加登陆用户)
1
> db.createCollection("t_users")(添加表)
{ "ok" : 1 }
> show collections(显示表)
system.indexes
system.users
system.version
t_users
> db.t_users.save({age:21})(存储数据)
WriteResult({ "nInserted" : 1 })
> db.t_users.find()(查询所有数据)
{ "_id" : ObjectId("53a2e45e4a674863b4ac5398"), "age" : 21 }
mongodb 删除数据库
use mymongo;
db.dropDatabase();
mongodb删除表
db.t_users.drop();
MongoDB服务停止:
在linux下大家停止很多服务都喜欢直接kill -9 PID,但是对于MongoDB如果执行了kill -9 PID,在下次启动时可能提示错误,导致服务无法启动,这个时候可以通过执行:
Java代码
- rm -f /app/hadoop/db/mongod.lock
也即删除指定数据目录下的mongod.lock文件即可。
正常停止方法:
kill -2 PID
或者
Java代码
先连接需要停止的服务,然后:
Java代码
- >use admin
- >db.shutdownServer();
这样也可以正常停止服务。
三、Java操作MongoDB示例1、 建立Test.java,完成简单的mongoDB数据库操作
- try {
- Mongo mg = new MongoClient("192.168.186.129", 8888);
- DB db = mg.getDB("mymongo");
- // 用于判断用户登录
- // if(!db.authenticate("sdap", "sdap123".toCharArray())){
- // 方法已经不建议使用
- // }
- Set<String> collectionNames = db.getCollectionNames();
- for (String string : collectionNames) {
- System.out.println(string);
- }
-
-
- DBCollection collection2 = db.getCollection("t_users2");
- collection2 = db.getCollection("t_users2");
- CarPasitionObj u = new CarPasitionObj();
- u.setLa(1231d);
- u.setLo(42342d);
- u.setPn("京1aaa");
- u.setTp(12);
- String obj2Json = JsonUtils.getSingletonInstance().obj2Json(u);
- BasicDBObject dbObject1=new BasicDBObject();
- dbObject1.put("key", "123131");
- dbObject1.put("value", obj2Json);
- collection2.save(dbObject1);
- <pre name="code" class="java"> BasicDBObject dbObject=new BasicDBObject();
- dbObject.put("key", "123131");
- DBCursor find = collection2.find(dbObject);
- while (find.hasNext()) {
- DBObject next = find.next();
- String key = (String)next.get("key");
- String json = (String)next.get("value");
- System.out.println(key);
- CarPasitionObj formJson = JsonUtils.getSingletonInstance().formJson(json, CarPasitionObj.class);
- System.out.println(formJson.getPn());
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
-
- }
下面贴上我自己的mongodb的工具类:
- /**
- * Project Name:main
- * File Name:MongodbCacheManagerUtil.java
- * Package Name:com.hdsx.taxi.driver.cq.cache
- * Date:2014年4月9日下午12:49:55
- * Copyright (c) 2014, sid Jenkins All Rights Reserved.
- *
- *
- */
-
- package com.hdsx.taxi.driver.cq.mongodb;
-
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.List;
-
- import org.apache.log4j.Logger;
-
- import com.hdsx.taxi.driver.cq.module.InitServletModule;
- import com.hdsx.taxi.driver.cq.tcp.util.JsonUtils;
- 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.MongoClient;
-
-
- /**
- * ClassName:MongodbCacheManagerUtil
- * Function: TODO ADD FUNCTION.
- * Reason: TODO ADD REASON.
- * Date: 2014年4月9日 下午12:49:55
- * @author sid
- * @see
- */
- public class MongodbManagerUtil {
- private static final Logger logger = Logger.getLogger(MongodbManagerUtil.class);
-
- private Mongo mg = null;
- private DB db = null;
-
- private volatile static MongodbManagerUtil singleton = null;
-
- public static final String KEY = "key";
-
- public static final String VALUE = "value";
-
- public static MongodbManagerUtil getSingletonInstance() {
- if (singleton == null) {
- synchronized (MongodbManagerUtil.class) {
- if (singleton == null) {
- singleton = new MongodbManagerUtil();
- }
- }
- singleton = new MongodbManagerUtil();
- }
- return singleton;
- }
-
- private MongodbManagerUtil() {
- if (logger.isDebugEnabled()) {
- logger.debug("MongodbCacheManagerUtil() - start "); //$NON-NLS-1$
- }
- try {
- mg = new MongoClient("192.168.186.129", 8888);
- db = mg.getDB("mymongo");
- } catch (UnknownHostException e) {
- e.printStackTrace();
-
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("MongodbCacheManagerUtil() - end"); //$NON-NLS-1$
- }
- }
-
- /**
- *
- * getCache:(获取缓存对象).
- *
- * @author sid
- * @param name
- * @return
- */
- public DBCollection getCache(String name){
- return this.db.getCollection(name);
- }
- /**
- *
- * put:(在指定缓存对象中加入需要缓存的对象).
- *
- * @author sid
- * @param cacheName
- * @param key
- * @param value
- */
- public void put(String cacheName, String key, Object value) {
- DBCollection cache = this.db.getCollection(cacheName);
- String obj2Json = JsonUtils.getSingletonInstance().obj2Json(value);
- BasicDBObject obj = new BasicDBObject();
- obj.put(MongodbManagerUtil.KEY, key);
- obj.put(MongodbManagerUtil.VALUE, obj2Json);
- BasicDBObject basicDBObject = new BasicDBObject(MongodbManagerUtil.KEY, key);
- int size = cache.find(basicDBObject).count();
- if (size==0) {
- cache.save(obj);
- }else{
- cache.update(basicDBObject, obj);
- }
- }
-
- /**
- *
- * get:(根据key从指定缓存对象中获取对象).
- *
- * @author sid
- * @param cacheName
- * @param key
- * @return
- */
- public <T> T get(String cacheName, String key, Class<T> classOfT) {
- DBCollection cache = this.db.getCollection(cacheName);
- List<DBObject> array = cache.find(new BasicDBObject(MongodbManagerUtil.KEY, key)).toArray();
- if (array == null||array.size()==0) {
- return null;
- }
- DBObject dbObject = array.get(0);
- String json = (String)dbObject.get(MongodbManagerUtil.VALUE);
-
- return JsonUtils.getSingletonInstance().formJson(json, classOfT);
- }
-
- /**
- *
- * remove:(从指定缓存对象中清除对象).
- *
- * @author sid
- * @param cacheName
- * @param key
- */
- public void remove(String cacheName, String key) {
- DBCollection cache = this.db.getCollection(cacheName);
- cache.remove(new BasicDBObject(MongodbManagerUtil.KEY,key));
- }
-
- /**
- *
- * getKeys:(获取keys列表).
- *
- * @author sid
- * @param cacheName
- * @return
- */
- public List<String> getKeys(String cacheName){
- List<String> list = new ArrayList<String>();
- DBCollection cache = this.db.getCollection(cacheName);
- DBCursor find = cache.find();
- while (find.hasNext()) {
- DBObject next = find.next();
- String key = (String) next.get(MongodbManagerUtil.KEY);
- list.add(key);
- }
- return list;
- }
-
- /**
- *
- * containsKey:(判断消息是否存在).
- *
- * @author sid
- * @param cacheName
- * @param key
- * @return
- */
- public Boolean containsKey(String cacheName,String key){
- DBCollection cache = this.db.getCollection(cacheName);
- BasicDBObject basicDBObject = new BasicDBObject(MongodbManagerUtil.KEY, key);
- int size = cache.find(basicDBObject).count();
- if (size==0) {
- return false;
- }else{
- return true;
- }
- }
- }
除了save、insert、update;mongodb还有remove等操作其中find方法可以指定查询条件:
大于等于:$gte
小于等于:$lte
不等于:$ne
demo:users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24)))
|
|