一、準備工作
下載java驅動包驅動包下載地址:http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
mongoDB下載:http://www.mongodb.org/
在線api:http://docs.mongodb.org/manual/applications/drivers/
二、安裝Mongo
1.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的文件,內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#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代碼
./mongo -host ip:port 先連接需要停止的服務,然後:
Java代碼
>use admin >db.shutdownServer();
這樣也可以正常停止服務。
三、Java操作MongoDB示例
1、 建立Test.java,完成簡單的mongoDB數據庫操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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的工具類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
/** *
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等操作 |