浏览代码

Mongodb使用示例

miaozy 4 年之前
父节点
当前提交
8a62bf0993

+ 361 - 1
ipu-mongodb-example/src/test/java/com/ai/ipu/example/mongodb/MongodbExample.java

@ -1,5 +1,365 @@
1 1
package com.ai.ipu.example.mongodb;
2 2

3
public class MongodbExample {
3
import com.ai.ipu.basic.log.ILogger;
4
import com.ai.ipu.basic.log.IpuLoggerFactory;
5
import com.ai.ipu.nosql.INoSql;
6
import com.ai.ipu.nosql.mongodb.MongoCacheFactory;
7
import com.ai.ipu.nosql.util.MongoConstant;
8
import com.alibaba.fastjson.JSONObject;
9
import junit.framework.TestCase;
4 10

11
import java.util.ArrayList;
12
import java.util.HashMap;
13
import java.util.List;
14
import java.util.Map;
15

16

17
/**
18
 * @author miaozy@asiainfo.com
19
 * @date 2020/9/27 7:36 下午
20
 * @desc mongoDB操作示例
21
 */
22
public class MongodbExample extends TestCase {
23

24
  transient protected ILogger log = IpuLoggerFactory.createLogger(MongodbExample.class);
25

26
  private String connName;
27
  private String dbName;
28
  private String tableName;
29
  private INoSql noSql;
30

31
  @Override
32
  protected void setUp() throws Exception {
33
    super.setUp();
34
    connName = "data";
35
    dbName = "test";
36
    tableName = "mycol1";
37
    noSql = MongoCacheFactory.getMongoDao(connName, dbName, tableName);
38
  }
39

40
  @Override
41
  protected void tearDown() throws Exception {
42
    //如果开启了事务开关,就要打开这里的提交代码
43
    //如果不需要支持事务,请注释这里的提交代码
44
    if (noSql != null)
45
      noSql.commitTransaction();
46
  }
47

48
  /**
49
   * 插入一条数据
50
   * @throws Exception
51
   */
52
  public void testExecuteInsert() throws Exception {
53
    JSONObject param = new JSONObject();
54
    param.put("name", "mongo");
55
    param.put("nikeName", "jack");
56
    param.put("ver", 7.0);
57
    param.put("age",21);
58
    param.put("info", "this is a test info");
59
    log.debug("before insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
60
    noSql.executeInsert(param);
61
    log.debug("after insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
62
  }
63

64

65
  /**
66
   * 插入一条数据
67
   *
68
   * @throws Exception
69
   */
70
  public void testExecuteInsert2() throws Exception {
71
    JSONObject param = new JSONObject();
72
    param.put("name", "mongo");
73
    log.debug("before insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
74

75
    JSONObject data = new JSONObject();
76
    data.put("name", "mongo");
77
    data.put("nickName", "tom");
78
    data.put("age", 21);
79
    Map info = new HashMap();
80
    info.put("ver", 7.0);
81
    data.put("info", info);
82

83
    noSql.executeInsert(data);
84
    log.debug("after insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
85
  }
86

87
  /**
88
   * 删除符合条件的所有数据
89
   *
90
   * @throws Exception
91
   */
92
  public void testExecuteDeleteMany() throws Exception {
93
    JSONObject param = new JSONObject();
94
    param.put("nickName", "tom1");
95
    noSql.executeDeleteMany(param.toJSONString());
96
  }
97

98
  /**
99
   * 删除collection里最后一条符合查询条件的记录
100
   *
101
   * @throws Exception
102
   */
103
  public void testExecuteDeleteLast() throws Exception {
104
    JSONObject param = new JSONObject();
105
    param.put("nickName", "miaozy10");
106
    noSql.executeDeleteLast(param.toJSONString());
107
  }
108

109
  /**
110
   * 更新collection里所有符合更新条件的记录
111
   *
112
   * @throws Exception
113
   */
114
  public void testExecuteUpdateMany() throws Exception {
115
    JSONObject cond = new JSONObject();
116
    cond.put("nickName", "miaozy");
117
    JSONObject field = new JSONObject();
118
    field.put("name", "1256");
119
    noSql.executeUpdateMany(cond.toJSONString(), field.toJSONString());
120
  }
121

122
  /**
123
   * 更新collection里所有符合更新条件的第一条记录
124
   *
125
   * @throws Exception
126
   */
127
  public void testExecuteUpdateFirst() throws Exception {
128
    JSONObject cond = new JSONObject();
129
    cond.put("nickName", "miaozy");
130
    JSONObject field = new JSONObject();
131
    field.put("name", "mongo");
132
    noSql.executeUpdateFirst(cond.toJSONString(), field.toJSONString());
133
  }
134

135
  /**
136
   * 更新collection里所有符合更新条件的最后一条记录
137
   *
138
   * @throws Exception
139
   */
140
  public void testExecuteUpdateLast() throws Exception {
141
    JSONObject cond = new JSONObject();
142
    cond.put("nickName", "miaozy");
143
    JSONObject field = new JSONObject();
144
    field.put("name", "mongo");
145
    noSql.executeUpdateLast(cond.toJSONString(), field.toJSONString());
146
  }
147

148

149
  /**
150
   * 返回collection里所有符合条件的记录数
151
   *
152
   * @throws Exception
153
   */
154
  public void testTakeRecordNum() throws Exception {
155
    JSONObject cond = new JSONObject();
156
    cond.put("nickName", "miaozy");
157
    log.debug("符合条件记录数:" + noSql.takeRecordNum(cond.toJSONString()));
158
  }
159

160
  /**
161
   * 查询符合条件的首记录(升序)
162
   *
163
   * @throws Exception
164
   */
165
  public void testExecuteSelectOne() throws Exception {
166
    JSONObject cond = new JSONObject();
167
    cond.put("nickName", "miaozy");
168
    log.debug("查询结果为:" + noSql.executeSelectOne(cond.toJSONString(), "{\"_id\":1}"));
169
  }
170

171
  /**
172
   * 查询符合条件的首记录(返回指定字段)
173
   *
174
   * @throws Exception
175
   */
176
  public void testExecuteSelectOne2() throws Exception {
177
    JSONObject cond = new JSONObject();
178
    cond.put("nickName", "苗子阳");
179
    JSONObject selectField = new JSONObject();
180
    selectField.put("name", 1);//1,返回。0不返回
181
    log.debug("查询结果为:" + noSql.executeSelectOne(cond.toJSONString(), selectField.toJSONString(), "{\"_id\":1}"));
182
  }
183

184
  /**
185
   * 查询符合条件的最后一条记录
186
   *
187
   * @throws Exception
188
   */
189
  public void testExecuteSelectLast() throws Exception {
190
    JSONObject condParam = new JSONObject();
191
    condParam.put("nickName", "tom");
192
    JSONObject sortParam = new JSONObject();
193
    sortParam.put("_id", -1);
194
    log.debug("查询结果为:" + noSql.executeSelect(condParam.toJSONString(), sortParam.toJSONString(), 1));
195
  }
196

197
  /**
198
   * 查询符合条件的所有数据
199
   *
200
   * @throws Exception
201
   */
202
  public void testExecuteSelect() throws Exception {
203
    JSONObject cond = new JSONObject();
204
    cond.put("nickName", "tom");
205
    JSONObject sort = new JSONObject();
206
    sort.put("_id", 1);
207
    log.debug("查询结果为:" + noSql.executeSelect(cond.toJSONString(), sort.toJSONString()));
208
  }
209

210
  /**
211
   * 查询符合条件的所有数据(分页)
212
   *
213
   * @throws Exception
214
   */
215
  public void testExecuteSelectByPage() throws Exception {
216
    JSONObject cond = new JSONObject();
217
    cond.put("nickName", "tom");
218
    log.debug("查询结果为:" + noSql.executeSelect(cond.toJSONString()));
219
  }
220

221
  /**
222
   * 设置返回记录的最大条数,查询符合条件的数据。
223
   * 类似mysql的limit
224
   * 类似oracle的rownum
225
   * 类似sqlserver的top
226
   *
227
   * @throws Exception
228
   */
229
  public void testExecuteSelect2() throws Exception {
230
    JSONObject cond = new JSONObject();
231
    cond.put("nickName", "tom");
232
    JSONObject sort = new JSONObject();
233
    sort.put("_id", 1);
234
    log.debug("查询结果为:" + noSql.executeSelect(cond.toJSONString(), sort.toJSONString(), 1));
235
  }
236

237
  /**
238
   * 查询符合条件,指定返回字段,并对结果排序
239
   *
240
   * @throws Exception
241
   */
242
  public void testExecuteSelect3() throws Exception {
243
    JSONObject cond = new JSONObject();
244
    cond.put("nickName", "tom");
245
    JSONObject sort = new JSONObject();
246
    sort.put("_id", 1);
247
    JSONObject selectField = new JSONObject();
248
    selectField.put("name", 1);//1,返回。0不返回)
249
    log.debug("查询结果为:" + noSql.executeSelect(cond.toJSONString(), selectField.toJSONString(), sort.toJSONString(), 1));
250
  }
251

252

253
  /**
254
   * 大于,大于等于
255
   * 等于,不等于
256
   * 小于,小于等于
257
   *
258
   * @throws Exception
259
   */
260
  public void testExecuteSelect4() throws Exception {
261
    JSONObject cond = new JSONObject();
262
    //cond.put(MongoConstant.ConditionalOperator.GREATOR_THAN,"4");//大于
263
    //cond.put(MongoConstant.ConditionalOperator.GREATOR_THAN_OR_EQUAL,"4");//大于等于
264
    //cond.put(MongoConstant.ConditionalOperator.EQUAL_TO,"3");//等于
265
    cond.put(MongoConstant.ConditionalOperator.NOT_EQUAL_TO, "3");//不等于
266
    //cond.put(MongoConstant.ConditionalOperator.LESS_THAN,"3");//小于
267
    //cond.put(MongoConstant.ConditionalOperator.LESS_THAN_OR_EQUAL,"2");//小于等于
268
    JSONObject param = new JSONObject();
269
    param.put("age", cond);
270
    List<String> ret = noSql.executeSelect(param.toJSONString(), "{}");
271
    log.debug("符合条件的数据有" + ret.size() + "条");
272
    log.debug("查询结果为:" + ret.toString());
273
  }
274

275
  /**
276
   * in
277
   * not in
278
   *
279
   * @throws Exception
280
   */
281
  public void testExecuteSelect5() throws Exception {
282
    JSONObject cond = new JSONObject();
283
    String[] data = {"4", "5"};
284
    //cond.put(MongoConstant.ConditionalOperator.IN,data);//in
285
    cond.put(MongoConstant.ConditionalOperator.NOT_IN, data);//not in
286
    JSONObject param = new JSONObject();
287
    param.put("age", cond);
288
    List<String> ret = noSql.executeSelect(param.toJSONString(), "{}");
289
    log.debug("符合条件的数据有" + ret.size() + "条");
290
    log.debug("查询结果为:" + ret.toString());
291
  }
292

293
  /**
294
   * and
295
   * or
296
   *
297
   * @throws Exception
298
   */
299
  public void testExecuteSelect6() throws Exception {
300
    JSONObject param = new JSONObject();
301
    JSONObject cond1 = new JSONObject();
302
    JSONObject cond2 = new JSONObject();
303
    cond1.put(MongoConstant.ConditionalOperator.LESS_THAN, "4");
304
    cond2.put(MongoConstant.ConditionalOperator.GREATOR_THAN, "2");
305
    List list = new ArrayList();
306
    Map info = new HashMap();
307
    info.put("age", cond1);
308
    list.add(info);
309
    info = new HashMap();
310
    info.put("age", cond2);
311
    list.add(info);
312
    //param.put(MongoConstant.RelationalOperator.OR, list);//or
313
    param.put(MongoConstant.RelationalOperator.AND, list);//and
314
    List<String> ret = noSql.executeSelect(param.toJSONString(), "{}");
315
    log.debug("符合条件的数据有" + ret.size() + "条");
316
    log.debug("查询结果为:" + ret.toString());
317
  }
318

319
  /**
320
   * not
321
   *
322
   * @throws Exception
323
   */
324
  public void testExecuteSelect7() throws Exception {
325
    JSONObject param = new JSONObject();
326
    JSONObject cond = new JSONObject();
327
    cond.put(MongoConstant.ConditionalOperator.GREATOR_THAN, "2");
328
    JSONObject cond1 = new JSONObject();
329
    cond1.put(MongoConstant.RelationalOperator.NOT, cond);
330

331
    param.put("age", cond1);
332

333
    List<String> ret = noSql.executeSelect(param.toJSONString(), "{}");
334
    log.debug("符合条件的数据有" + ret.size() + "条");
335
    log.debug("查询结果为:" + ret.toString());
336

337
  }
338

339
  /**
340
   * 多条件查询
341
   * select name,nickName,count(1) totalNum,sum(age) sumAge
342
   * from mycol1 where name != 'mike'
343
   * group by name,nickName
344
   * having sumAge >10
345
   * order by sumAge asc
346
   * @throws Exception
347
   */
348
  public void testExecuteSelect11() throws Exception {
349
    JSONObject cond = new JSONObject();
350
    cond.put("name", "{ $ne : \"mike\" }");
351
    JSONObject sort = new JSONObject();
352
    sort.put("totalAge", 1);
353

354
    JSONObject havingParam = new JSONObject();
355
    havingParam.put("totalAge", "{ $gt : 10}");
356

357
    JSONObject sumField = new JSONObject();
358
    sumField.put("totalAge", "age");
359

360
    JSONObject selectField = new JSONObject();
361
    selectField.put("name", 1);
362
    selectField.put("nickName", 1);
363
    log.debug("查询结果为:" + noSql.executeAggregateSelect(selectField.toJSONString(), cond.toJSONString(), sort.toJSONString(), havingParam.toJSONString(), sumField.toJSONString(), true));
364
  }
5 365
}

+ 141 - 0
ipu-mongodb-example/src/test/java/com/ai/ipu/example/mongodb/MongodbExampleWithSql.java

@ -0,0 +1,141 @@
1
package com.ai.ipu.example.mongodb;
2
3
import com.ai.ipu.basic.log.ILogger;
4
import com.ai.ipu.basic.log.IpuLoggerFactory;
5
import com.ai.ipu.nosql.INoSql;
6
import com.ai.ipu.nosql.mongodb.MongoCacheFactory;
7
import com.alibaba.fastjson.JSONObject;
8
import junit.framework.TestCase;
9
10
import java.util.HashMap;
11
import java.util.Map;
12
13
/**
14
 * @author miaozy@asiainfo.com
15
 * @desc 使用标准SQL操作mongoDB
16
 * @date 2020/9/27 7:36 下午
17
 */
18
public class MongodbExampleWithSql extends TestCase {
19
20
  transient protected ILogger log = IpuLoggerFactory.createLogger(MongodbExampleWithSql.class);
21
22
  private String connName;
23
  private String dbName;
24
  private String tableName;
25
  private INoSql noSql;
26
27
  @Override
28
  protected void setUp() throws Exception {
29
    super.setUp();
30
    connName = "data";
31
    dbName = "test";
32
    tableName = "mycol1";
33
    noSql = MongoCacheFactory.getMongoDao(connName, dbName, tableName);
34
  }
35
36
  @Override
37
  protected void tearDown() throws Exception {
38
    //如果开启了事务开关,就要打开这里的提交代码
39
    //如果不需要支持事务,请注释这里的提交代码
40
    if (noSql != null)
41
      noSql.commitTransaction();
42
  }
43
44
  /**
45
   * 使用标准sql插入一条数据
46
   *@throws Exception
47
   */
48
  public void testExecuteInsert2() throws Exception {
49
    JSONObject param = new JSONObject();
50
    param.put("name", "test");
51
    log.debug("before insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
52
    noSql.executeInsert("insert into mycol1 (name, nickName, remarks, age) values ('test','this is a test','2',20)");
53
    log.debug("after insert, num is :" + noSql.takeRecordNum(param.toJSONString()));
54
  }
55
56
  /**
57
   * 使用标准sql删除mongodb数据
58
   * @throws Exception
59
   */
60
  public void testExecuteDelete() throws Exception {
61
    noSql.executeDelete("delete from mycol1 where name = 'test'");
62
  }
63
64
  /**
65
   * 使用标准sql修改mongodb数据
66
   * @throws Exception
67
   */
68
  public void testExecuteUpdate() throws Exception {
69
    noSql.executeUpdate("update mycol1 set remarks = '2' where name = 'test'");
70
  }
71
72
  /**
73
   * 使用标准SQL,where条件查询mongodb
74
   * 简单的汇总计数
75
   * @throws Exception
76
   */
77
  public void testExecuteSelect2() throws Exception {
78
    log.debug("查询结果为:" + noSql.executeSelect("select count(1) totalNum from mycol1 where name != 'mike' "));
79
  }
80
81
  /**
82
   * 使用标准SQL查询mongodb
83
   * 普通查询 升序,降序
84
   * @throws Exception
85
   */
86
  public void testExecuteSelect3() throws Exception {
87
    //log.debug("升序查询结果为:" + noSql.executeSelect("select * from mycol1 where name != 'mike' order by age asc"));
88
    log.debug("降序查询结果为:" + noSql.executeSelect("select * from mycol1 where name != 'mike' order by age desc"));
89
  }
90
91
  /**
92
   * 使用标准SQL查询mongodb
93
   * 条件:大于,小于,等于
94
   * @throws Exception
95
   */
96
  public void testExecuteSelect4() throws Exception {
97
    //log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age > 20"));
98
    log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age = 20"));
99
    //log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age < 20"));
100
  }
101
102
  /**
103
   * 使用标准SQL查询mongodb
104
   * 条件:大于等于,小于等于
105
   * @throws Exception
106
   */
107
  public void testExecuteSelect5() throws Exception {
108
    log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age >= 20"));
109
    //log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age <= 20"));
110
  }
111
112
  /**
113
   * 使用标准SQL查询mongodb
114
   * 条件:in,not in
115
   * @throws Exception
116
   */
117
  public void testExecuteSelect6() throws Exception {
118
    //log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age in (10,20)"));
119
    log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age not in (20)"));
120
  }
121
122
  /**
123
   * 使用标准SQL查询mongodb
124
   * 条件:and,or
125
   * @throws Exception
126
   */
127
  public void testExecuteSelect7() throws Exception {
128
    //log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age >= 20 and age < 21"));
129
    log.debug("查询结果为:" + noSql.executeSelect("select * from mycol1 where age >= 20 or age < 21"));
130
  }
131
132
  /**
133
   * 使用标准SQL查询mongodb
134
   * 条件:group by,having,order by
135
   * 分类汇总
136
   * @throws Exception
137
   */
138
  public void testExecuteSelect1() throws Exception {
139
    log.debug("查询结果为:" + noSql.executeSelect("select name,nickName,sum(age) sumAge,count(1) totalNum from mycol1 where name != 'mike' group by name,nickName  having sumAge>=10 order by sumAge desc"));
140
  }
141
}

+ 6 - 6
ipu-mongodb-example/src/test/resources/ipu-nosql.xml

@ -12,12 +12,12 @@
12 12
13 13
    <connection name="data" type="mongo">
14 14
        <servers>
15
            <server ip="10.1.236.121" port="11000" />
16
            <server ip="10.1.236.121" port="11010" />
17
            <server ip="10.1.236.121" port="11020" />
15
            <server ip="47.105.160.21" port="10030" />
16
            <server ip="47.105.160.21" port="10040" />
17
            <server ip="47.105.160.21" port="10050" />
18 18
        </servers>
19 19
        <!-- 连接时数据库名,不做身份验证时可空;身份认证时必填 -->
20
        <config name="authSource" value="admin"/>
20
        <config name="authSource" value="test"/>
21 21
        <!-- 认证机制,不做身份验证时可空;身份认证时必填。mongo3.0及更高版本缺省是SCRAM-SHA-1 -->
22 22
        <!-- mongo2.6以前缺省是MONGODB-CR, mongo4.0及更高版本已经不再支持-->
23 23
        <!-- 支持SCRAM-SHA-1、SCRAM-SHA-256-->
@ -27,9 +27,9 @@
27 27
        <config name="userName" value="ipuOper"/>
28 28
        <!-- 加密后的用户密码,不做身份验证时可空;身份认证时必填 -->
29 29
        <!-- 加密算法需要用一对@@包含,并且放在密码的最前面。如果没有发现加密算法,则为明文密码  -->
30
        <config name="encryptedPasswd" value="@DES@cqKYnoRap2YV9L7xEQ4fyw=="/>
30
        <config name="encryptedPasswd" value="@DES@L4+tgpw/Q67MvcM4mN1AhQ=="/>
31 31
        <!-- 解密秘钥 ,可为空 -->
32
        <config name="decryptedKey" value="Mongo4@121#_3$"/>
32
        <config name="decryptedKey" value="325m@#$rt4vt"/>
33 33
        <!-- 自定义解密算法需要在pom.xml里引入所需jar,并在此声明带全包名的类 -->
34 34
        <config name="decryptedClass" value="com.ai.ipu.nosql.util.DecryptUtil"/>
35 35
        <!-- 自定义解密算法的解密算法,加密后的秘钥(可为空,为空则只有1个参数)、密码串是算法的2个参数  -->

+ 15 - 0
ipu-mongodb-example/src/test/resources/log4j2.xml

@ -0,0 +1,15 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<Configuration status="DEBUG">
3
    <Appenders>
4
        <Console name="Console" target="SYSTEM_OUT">
5
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
6
        </Console>
7
    </Appenders>
8
    <Loggers>
9
        <Root level="DEBUG">
10
            <AppenderRef ref="Console"/>
11
        </Root>
12
        <logger name="com.ai" level="DEBUG"></logger>
13
        <logger name="org.springframework" level="INFO"></logger>
14
    </Loggers>
15
</Configuration>