Spring MongoTemplate中保存数据insert 和save方法的区别

测试方法

@PostMapping("/mongoSave") public Response mongoSave(){ Map map = new HashMap<>(); map.put("_id", "10086"); map.put("name", "songfayuan"); map.put("age", "26"); map.put("wechat", "SFY54420"); this.mongoTemplate.save(map, "collectionName1"); this.mongoTemplate.insert(map, "collectionName2"); return Response.successResponse("新增成功"); }

区别 插入重复数据
insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
【Spring MongoTemplate中保存数据insert 和save方法的区别】批操作
insert: 可以一次性插入一整个列表,而不用进行遍历操作,效率相对较高
save: 需要遍历列表,进行一个个的插入
insert插入抛异常:
{ "msg": "Write failed with error code 11000 and error message 'E11000 duplicate key error collection: collection.collectionName2 index: _id_ dup key: { : \"10086\" }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: collection.collectionName2 index: _id_ dup key: { : \"10086\" }'", "code": 500, "data": null }

    推荐阅读