javascript:void(0)
一、准备工作
1、建立maven项目,添加所需依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.3</version>
</dependency>
当然也可以建立java project,下载mongoDB对Java支持的驱动包,然后拷贝jar文件到lib下
2、开启mongo服务,建立测试类进行测试
二、完整源码如下:
[java] view plain copy
1. package com.shxt.mongo;
2.
3. import java.net.UnknownHostException;
4. import java.util.ArrayList;
5. import java.util.List;
6.
7. import org.bson.types.ObjectId;
8. import org.junit.After;
9. import org.junit.Before;
10. import org.junit.Test;
11.
12. import com.mongodb.BasicDBObject;
13. import com.mongodb.DB;
14. import com.mongodb.DBCollection;
15. import com.mongodb.DBCursor;
16. import com.mongodb.DBObject;
17. import com.mongodb.Mongo;
18. import com.mongodb.MongoClient;
19. import com.mongodb.util.JSON;
20.
21. /**
22. * MongDB之CRUD
23. * @author 范晓东
24. * @ClassName: TestMongo
25. * @Version 1.0
26. * @ModifiedBy
27. * @Copyright shxt
28. * @date 2013-9-27 下午08:21:49
29. * @description
30. */
31. public class TestMongo {
32.
33. private Mongo mg = null;
34. private DB db;
35. private DBCollection users;
36.
37. @Before
38. public void setUp() throws UnknownHostException {
39. // 创建一个MongoDB的数据库连接对象
40. new MongoClient("localhost", 27017);
41. //验证模式登录(如果不设置验证模块,可直接登录)
42. //想要登录验证模块生效,需在命令行下输入1->mongo 2->use admin 3->db.addUser("root","root123"); 4->db.auth("root","root123");
43. "admin");
44. boolean bool =admin.authenticate("root", "root123".toCharArray());
45. if (bool){
46. //login success
47. //获得一个test的数据库,如果该数据库不存在,会自动创建
48. "test");
49. }
50. // 获取一个聚集集合DBCollection,相当于我们的数据库表
51. "users");
52. }
53.
54. @Test
55. public void testQuery() {
56. //查询所有的数据库
57. for (String name : mg.getDatabaseNames()) {
58. "dbName: " + name);
59. }
60. //查询所有的聚集集合
61. for (String name : db.getCollectionNames()) {
62. "collectionName: " + name);
63. }
64. //查询所有的数据
65. DBCursor cur = users.find();
66. while (cur.hasNext()) {
67. System.out.println(cur.next());
68. }
69. //其它
70. System.out.println(cur.count());
71. System.out.println(users.count());
72. System.out.println(cur.getCursorId());
73. //JSON对象转换
74. }
75.
76. @Test
77. public void testQuery2(){
78. //根据id查询
79. new BasicDBObject("_id", new ObjectId("5243871a0609f38c8a7a5ccd"))).toArray();
80. 0).get("name"));
81.
82. //根据age查询,从第一条开始取,取3条数据
83. new BasicDBObject();
84. "age", new BasicDBObject("$gte", 20));
85. 0).limit(3);
86. System.out.println(cur.count());
87. while (cur.hasNext()) {
88. System.out.println(cur.next());
89. }
90.
91. //查询age!=25
92. //users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray();
93. //查询age in 25/26/27
94. //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray();
95. //查询age not in 25/26/27
96. //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray();
97. //查询存在age的数据
98. //users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray();
99. //只查询age属性
100. //users.find(null, new BasicDBObject("age", true)).toArray();
101.
102. //只查询一条数据,多条取第一条
103. //users.findOne();
104. //users.findOne(new BasicDBObject("age", 26));
105. //users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true));
106.
107. //查询age=25的数据并删除
108. //users.findAndRemove(new BasicDBObject("age", 25));
109. //查询age=26的数据,并且修改name的值为abc
110. //users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "abc"));
111. }
112.
113. @Test
114. public void testAdd() {
115. new BasicDBObject();
116. "name", "fxd");
117. "age", 21);
118. "sex", "男");
119. users.save(user);
120. //查看是否添加成功
121. DBCursor cur = users.find();
122. while (cur.hasNext()) {
123. System.out.println(cur.next());
124. }
125. }
126.
127. @Test
128. public void testAdd2() {
129. new BasicDBObject("name","张三");
130. new BasicDBObject("age",20);
131. users.insert(user1,user2);
132. //查看是否添加成功
133. DBCursor cur = users.find();
134. while (cur.hasNext()) {
135. System.out.println(cur.next());
136. }
137. }
138.
139. @Test
140. public void testAdd3() {
141. new BasicDBObject("name","张三");
142. new BasicDBObject("age",20);
143. new ArrayList<DBObject>();
144. list.add(user1);
145. list.add(user2);
146. users.insert(list);
147. //查看是否添加成功
148. DBCursor cur = users.find();
149. while (cur.hasNext()) {
150. System.out.println(cur.next());
151. }
152. }
153.
154. @Test
155. public void testRemove(){
156. new BasicDBObject("_id", new ObjectId("524378680609ad5717421c6a")));
157. //users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24)));
158. }
159.
160. @Test
161. public void update(){
162. //=update users set age=17 where name='fxd';
163. users.update(
164. new BasicDBObject("name","fxd"),//new BasicDBObject().append("name","fxd"),
165. new BasicDBObject("$set" ,new BasicDBObject("age",17)),
166. false,//如果users中不存在age字段,是否更新,false表示不更新
167. false//只修改第一条,true表示修改多条
168. );
169. }
170.
171. @Test
172. public void update2(){
173. //批量修改,也可以用users.update(),把第四个参数改为true即可
174. //=update users set age=age+10 where name='fxd';
175. users.updateMulti(
176. new BasicDBObject().append("name","fxd"),
177. new BasicDBObject("$inc",new BasicDBObject("age", 10))
178. );
179. }
180.
181. @After
182. public void tearDown() {
183. if (mg != null) {
184. if (db != null) {
185. // 结束Mongo数据库的事务请求
186. try {
187. db.requestDone();
188. catch (Exception e) {
189. e.printStackTrace();
190. }
191. }
192. try {
193. mg.close();
194. catch (Exception e) {
195. e.printStackTrace();
196. }
197. null;
198. null;
199. }
200. }
201. }
[java] view plain copy