本篇博文为mongodb的curd中一篇,前面介绍简单的查询使用,这一篇重点则放在插入数据;
I. 基本使用
首先是准备好基本环境,可以参考博文
1. 新增一条数据
MongoDB一个基本数据称为document,和mysql不一样,没有强制约束哪些字段,可以随意的插入,下面是一个简单的插入演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
private static final String COLLECTION_NAME = "demo";
@Autowired private MongoTemplate mongoTemplate;
public void insert() { JSONObject object = new JSONObject(); object.put("name", "一灰灰blog"); object.put("desc", "欢迎关注一灰灰Blog"); object.put("age", 28);
mongoTemplate.insert(object, COLLECTION_NAME);
JSONObject ans = mongoTemplate .findOne(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(28)), JSONObject.class, COLLECTION_NAME); System.out.println(ans); }
|
使用的关键地方为一行: mongoTemplate.insert(object, COLLECTION_NAME);
- 第一个参数为待插入的document
- 第二个参数为collection name (相当于mysql的table)
执行后输出结果为如下
1
|
{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":28,"desc":"欢迎关注一灰灰Blog"}
|
2. 批量插入
一次插入多条记录,传集合进去即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public void insertMany() { List<Map<String, Object>> records = new ArrayList<>(); for (int i = 0; i < 3; i++) { Map<String, Object> record = new HashMap<>(4); record.put("wechart", "一灰灰blog"); record.put("blog", Arrays.asList("http://spring.hhui.top", "http://blog.hhui.top")); record.put("nums", 210); record.put("t_id", i); records.add(record); }
mongoTemplate.insert(records, COLLECTION_NAME);
List<Map> result = mongoTemplate.find(new Query(Criteria.where("wechart").is("一灰灰blog")), Map.class, COLLECTION_NAME); System.out.println("Query Insert Records: " + result); }
|
返回结果如下:
1
|
Query Insert Records: [{t_id=0, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5022, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}, {t_id=1, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5023, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}, {t_id=2, wechart=一灰灰blog, _id=5c49b07cd5b7ee435cbe5024, blog=[http://spring.hhui.top, http://blog.hhui.top], nums=210}]
|
3. upsert,不存在才插入
我们希望在插入之前,判断数据是否存在,如果不存在则插入;如果存在则更新;此时就可以采用upsert来使用,一般三个参数
1
|
mongoTemplate.upsert(Query query, Update update, String collectionName)
|
第一个为查询条件,第二个为需要更新的字段,最后一个指定对应的collection,一个简单的实例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public void upsertNoMatch() { UpdateResult upResult = mongoTemplate.upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(100)), new Update().set("age", 120).addToSet("add", "额外增加"), COLLECTION_NAME); System.out.println("nomatch upsert return: " + upResult);
List<JSONObject> re = mongoTemplate .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)), JSONObject.class, COLLECTION_NAME); System.out.println("after upsert return should not be null: " + re); System.out.println("------------------------------------------"); }
|
输出结果如下:
1 2 3
|
nomatch upsert return: AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=BsonObjectId{value=5c49b07ce6652f7e1add1ea2}} after upsert return should not be null: [{"add":["额外增加"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":120}] ------------------------------------------
|
4. upsert,存在则更新
前面的demo是演示不存在,那么存在数据呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
public void upsertOneMatch() { UpdateResult result = mongoTemplate.upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)), new Update().set("age", 100), COLLECTION_NAME); System.out.println("one match upsert return: " + result);
List<JSONObject> ans = mongoTemplate .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(100)), JSONObject.class, COLLECTION_NAME); System.out.println("after update return should be one: " + ans); System.out.println("------------------------------------------"); }
|
输出结果如下,注意下面的输出数据的 _id
,正视前面插入的那条数据,两个数据唯一的不同,就是age被修改了
1 2
|
one match upsert return: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null} after update return should be null: [{"add":["额外增加"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":100}]
|
5. upsert,多条满足时
如果query条件命中多条数据,怎么办?会修改几条数据呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public void upsertTwoMatch() { System.out.println("------------------------------------------"); List<JSONObject> re = mongoTemplate .find(new Query(Criteria.where("name").is("一灰灰blog").and("age").in(Arrays.asList(28, 100))), JSONObject.class, COLLECTION_NAME); System.out.println("original record: " + re);
UpdateResult result = mongoTemplate .upsert(new Query(Criteria.where("name").is("一灰灰blog").and("age").in(Arrays.asList(28, 100))), new Update().set("age", 120), COLLECTION_NAME); System.out.println("two match upsert return: " + result);
re = mongoTemplate.find(new Query(Criteria.where("name").is("一灰灰blog").and("age").is(120)), JSONObject.class, COLLECTION_NAME); System.out.println("after upsert return size should be 1: " + re); System.out.println("------------------------------------------"); }
|
根据实际输出进行查看,发现只有一条数据被修改;另外一条保持不变,结果如下
1 2 3 4 5
|
------------------------------------------ original record: [{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":28,"desc":"欢迎关注一灰灰Blog"}, {"add":["额外增加"],"name":"一灰灰blog","_id":{"counter":14491298,"date":1548333180000,"machineIdentifier":15099183,"processIdentifier":32282,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":100}] two match upsert return: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null} after upsert return size should be 1: [{"name":"一灰灰blog","_id":{"counter":12472353,"date":1548333180000,"machineIdentifier":14006254,"processIdentifier":17244,"time":1548333180000,"timeSecond":1548333180,"timestamp":1548333180},"age":120,"desc":"欢迎关注一灰灰Blog"}] ------------------------------------------
|
II. 其他
0. 项目
相关博文
1. 一灰灰Blog
一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
2. 声明
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激