根据_id查询库里是否存在相关文档,如果已经存在就执行更新。如果不存在就插入。
来源:3-12 【更新文档】动手实战 - 使用更新操作符精确更新文档内容

默默小雨山
2019-11-07
public ResponseResult saveData(@RequestBody DeviceAttachedData attachedData) {
ResponseResult result = new ResponseResult();
try {
MongoClient client = new MongoClient(new MongoClientURI(“mongodb://******:27017”));
MongoDatabase mongoDatabase = client.getDatabase(“gaoxue_test”);
MongoCollection collection = mongoDatabase.getCollection(“Collections”);
List list = new ArrayList<>();
if (attachedData != null && attachedData.getAttachedDataList() != null && attachedData.getAttachedDataList().size() > 0) {
JSONArray json = JSONArray.fromObject(attachedData.getAttachedDataList());
JSONObject jsonOne;
Document document = new Document();
for (int i = 0; i < json.size(); i++) {
jsonOne = json.getJSONObject(i);
Map<String, String> map = new HashMap<>();
map.put(“A”, (String) jsonOne.get(“A”));
map.put(“B”, (String) jsonOne.get(“B”));
map.put(“C”, (String) jsonOne.get(“C”));
map.put(“D”, (String) jsonOne.get(“D”));
map.put(“E”, (String) jsonOne.get(“E”));
map.put(“F”, (String) jsonOne.get(“F”));
map.put(“G”, (String) jsonOne.get(“G”));
map.put(“H”, (String) jsonOne.get(“H”));
map.put(“I”, (String) jsonOne.get(“I”));
map.put(“J”, (String) jsonOne.get(“J”));
map.put(“K”, (String) jsonOne.get(“K”));
map.put(“L”, (String) jsonOne.get(“L”));
map.put(“isEdit”, (String) jsonOne.get(“isEdit”));
map.put(“status”, (String) jsonOne.get(“status”));
String id = String.valueOf(attachedData.getDeviceId());
document.append("_id",attachedData.getDeviceId());
document.append(id+i, map);
}
list.add(document);
collection.insertMany(list);
}
if (attachedData == null || attachedData.getAttachedDataList() == null || attachedData.getAttachedDataList().size() == 0) {
return null;
}
result.setData(null);
result.setSuccess(true);
} catch (Exception e) {
result.setErrMsg(“数据录入失败”);
}
return result;
}
老师,帮我看下,在这个基础上怎么改。
1回答
-
Stannum
2019-12-29
同学你好~记得你在私聊中提到这个问题已经解决了?可否关闭这个问题了呢?
00
相似问题